함수 gcd()

1 개요[ | ]

함수 gcd()

2 같이 보기[ | ]

3 C++[ | ]

#include <iostream>
#include <numeric>
using namespace std;

int main() {
    cout << gcd(12, 21) << endl; // 3
    cout << lcm(20, 8) << endl; // 40
}

4 Java[ | ]

import java.math.BigInteger;
public class MyClass {
    private static int gcd(int a, int b) {
        return BigInteger.valueOf(a).gcd(BigInteger .valueOf(b)).intValue();
    }
    public static void main(String args[]) {
        System.out.println( gcd(12,21) ); // 3
        System.out.println( gcd(20,8) ); // 40
    }
}

5 PHP[ | ]

gmp_gcd() 사용
function gcd($a,$b) { return gmp_intval(gmp_gcd($a,$b)); }
var_dump( gcd(12,21) );
# int(3)
var_dump( gmp_intval(gmp_gcd(12, 21)) );
# int(3)
echo gmp_gcd(12, 21) . "\n";
# 3
var_dump( gmp_gcd(12, 21) );
# object(GMP)#1 (1) {
#   ["num"]=>
#   string(1) "3"
# }
구현
function gcd($a, $b) { return $b ? gcd($b, $a%$b) : $a; }
var_dump( gcd(12, 21) );
var_dump( gcd(20, 8) );
# int(3)
# int(4)
function gcd($a, $b) { return ($a%$b) ? gcd($b,$a%$b) : $b; }
var_dump( gcd(12, 21) );
var_dump( gcd(20, 8) );
# int(3)
# int(4)

6 Python[ | ]

from math import gcd
print( gcd(12,21) ) # 3
print( gcd(20,8) )  # 4
def gcd(a,b):
    while b > 0:
        a, b = b, a % b
    return a

print( gcd(12,21) ) # 3
print( gcd(20,8) )  # 4
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}