여러 수의 최소 공배수를 어떻게 계산합니까?
지금까지 나는 두 숫자 사이에서만 그것을 계산할 수 있었다. 하지만 3개 이상의 숫자를 계산하기 위해 그것을 확장하는 방법을 모른다.
지금까지는 이렇게 했다.
LCM = num1 * num2 / gcd ( num1 , num2 )
gcd는 숫자에 대한 최대 공약수를 계산하는 함수이다. 유클리드 알고리즘 사용
그런데 3개 이상의 숫자를 어떻게 계산하는지 모르겠어요.
파이썬에서 (수정된 primes.py):
def gcd(a, b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""Return lowest common multiple."""
return a * b // gcd(a, b)
def lcmm(*args):
"""Return lcm of args."""
return reduce(lcm, args)
사용법:
>>> lcmm(100, 23, 98)
112700
>>> lcmm(*range(1, 20))
232792560
'reduce'는 그렇다:
>>> f = lambda a,b: "f(%s,%s)" % (a,b)
>>> print reduce(f, "abcd")
f(f(f(a,b),c),d)
function gcd(a, b){
// Euclidean algorithm
var t;
while (b != 0){
t = b;
b = a % b;
a = t;
}
return a;
}
function lcm(a, b){
return (a * b / gcd(a, b));
}
function lcmm(args){
// Recursively iterate through pairs of arguments
// i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))
if(args.length == 2){
return lcm(args[0], args[1]);
} else {
var arg0 = args[0];
args.shift();
return lcm(arg0, lcmm(args));
}
}
꼭 이래야겠어요 gnu. 대체하십시오 1 (C #):
static long LCM(long[] numbers)
{
return numbers.Aggregate(lcm);
}
static long lcm(long a, long b)
{
return Math.Abs(a * b) / GCD(a, b);
}
static long GCD(long a, long b)
{
return b == 0 ? a : GCD(b, a % b);
}
처음 보면, 이 때문에 일부 설명, 그냥 그렇게 하는 것이 이 코드는 선택해제합니다 doesn& # 39 조인트 t:
집계) 는 linq 확장명은 방법을 사용하여 잊지 수 있기 때문에 추가 시스템드링크 데이터베이스에구성원을 참조입니다.
전체 등록 정보를 얻을 수 있는 기능을 활용할 수 있도록 다소 lcm (a, b, c) = 리누머이블 통해 lcm (a, lcm (b, c)). [더 합계에서] [1]
유클리드 호제법 최대공약수 계산을 사용할 수 있습니다.
lcm 계산 /dev/raw/raw1 Abs ( *) / 최대공약수 (a, b) 인 감면은 이 최대공약수.
따라서, 희망
[1]: 이아스파스 https://msdn.microsoft.com/en-us/library/vstudio/bb548651 (v = vs. 100)
from sys import argv
def lcm(x,y):
tmp=x
while (tmp%y)!=0:
tmp+=x
return tmp
def lcmm(*args):
return reduce(lcm,args)
args=map(int,argv[1:])
print lcmm(*args)
$ python lcm.py 10 15 17
510
이것은 한 줄 광고문 아닌 임포트합니다 알파 (α) 의 파이썬 반환되기를 lcm 정수 1 부터 20 포함).
파이썬 3.5+ 임포트합니다:
from functools import reduce
from math import gcd
파이썬 2.7 임포트합니다:
from fractions import gcd
일반적인 논리를 폈다.
lcm = reduce(lambda x,y: x*y//gcd(x, y), range(1, 21))
참고로 모두 [파이썬 2] (https://docs.python.org/2/reference/expressions.html # 연산자 우선순위를 정한다) 및 [파이썬 3] (https://docs.python.org/3/reference/expressions.html # 연산자 우선순위를 정한다) '와' / / '등으로 인하여 ' 작동자 우선 순위 규칙, 해당 사업자들이 동일한 우선순위, 그들은 적용하십시오 왼쪽에서 오른쪽으로. , '등' ( ) / / 고말은 y// 'z' 아닌 'x (y//z)'. 일반적으로 두 다르게 결과를 얻을 수 있습니다. # 39 사단 않니다 중요 하지만, 이 wouldn& 없는 것과 같이 부동 소수점 장치당 [바닥 사단] (https://stackoverflow.com/a/183870/832230).
이것은 C # 포트 버질 Disgr4ce& # 39 의 된 구현.
public class MathUtils
{
/// <summary>
/// Calculates the least common multiple of 2+ numbers.
/// </summary>
/// <remarks>
/// Uses recursion based on lcm(a,b,c) = lcm(a,lcm(b,c)).
/// Ported from http://stackoverflow.com/a/2641293/420175.
/// </remarks>
public static Int64 LCM(IList<Int64> numbers)
{
if (numbers.Count < 2)
throw new ArgumentException("you must pass two or more numbers");
return LCM(numbers, 0);
}
public static Int64 LCM(params Int64[] numbers)
{
return LCM((IList<Int64>)numbers);
}
private static Int64 LCM(IList<Int64> numbers, int i)
{
// Recursively iterate through pairs of arguments
// i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))
if (i + 2 == numbers.Count)
{
return LCM(numbers[i], numbers[i+1]);
}
else
{
return LCM(numbers[i], LCM(numbers, i+1));
}
}
public static Int64 LCM(Int64 a, Int64 b)
{
return (a * b / GCD(a, b));
}
/// <summary>
/// Finds the greatest common denominator for 2 numbers.
/// </summary>
/// <remarks>
/// Also from http://stackoverflow.com/a/2641293/420175.
/// </remarks>
public static Int64 GCD(Int64 a, Int64 b)
{
// Euclidean algorithm
Int64 t;
while (b != 0)
{
t = b;
b = a % b;
a = t;
}
return a;
}
}'
어떤 함수 com/go/downloads_kr lcm 목록 번호:
def function(l):
s = 1
for i in l:
s = lcm(i, s)
return s
이것은 in 스위프트 .
// Euclid's algorithm for finding the greatest common divisor
func gcd(_ a: Int, _ b: Int) -> Int {
let r = a % b
if r != 0 {
return gcd(b, r)
} else {
return b
}
}
// Returns the least common multiple of two numbers.
func lcm(_ m: Int, _ n: Int) -> Int {
return m / gcd(m, n) * n
}
// Returns the least common multiple of multiple numbers.
func lcmm(_ numbers: [Int]) -> Int {
return numbers.reduce(1) { lcm($0, $1) }
}
다음은 PHP 구현.
// https://stackoverflow.com/q/12412782/1066234
function math_gcd($a,$b)
{
$a = abs($a);
$b = abs($b);
if($a < $b)
{
list($b,$a) = array($a,$b);
}
if($b == 0)
{
return $a;
}
$r = $a % $b;
while($r > 0)
{
$a = $b;
$b = $r;
$r = $a % $b;
}
return $b;
}
function math_lcm($a, $b)
{
return ($a * $b / math_gcd($a, $b));
}
// https://stackoverflow.com/a/2641293/1066234
function math_lcmm($args)
{
// Recursively iterate through pairs of arguments
// i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))
if(count($args) == 2)
{
return math_lcm($args[0], $args[1]);
}
else
{
$arg0 = $args[0];
array_shift($args);
return math_lcm($arg0, math_lcmm($args));
}
}
// fraction bonus
function math_fraction_simplify($num, $den)
{
$g = math_gcd($num, $den);
return array($num/$g, $den/$g);
}
var_dump( math_lcmm( array(4, 7) ) ); // 28
var_dump( math_lcmm( array(5, 25) ) ); // 25
var_dump( math_lcmm( array(3, 4, 12, 36) ) ); // 36
var_dump( math_lcmm( array(3, 4, 7, 12, 36) ) ); // 252
크레딧 gnu. orghttp://www. @T3db0t 아버지와 함께 오토메이티드 위 (ecma 스타일 code).
할 수 있어 또 다른 방법은 - ᄂ씨 숫자임 있어야 하겠습니다. 또 다른 한 쌍의 연속적입니다 번호 및 저장 시행하십시오 해당 lcm 어레이입니다. 이렇게 하면 처음에 이터레이션에 이터레이션에 프로그램 n/2 않습니다. 다음 (0.1), (2.3) 와 같은 수거 페어당 0 부터 드릴링됩니다. 컴퓨팅 및 저장 그들의 LCM 다른 컨텍스트에서는 어레이입니다. 이렇게 될 때까지 남아 있는 한 어레이입니다. (lcm 홀수입니다 경우 n 은 찾을 수 없습니다)
그냥 재미로 쉘로 (거의 모든 쉘로) 구축.
#!/bin/sh
gcd() { # Calculate $1 % $2 until $2 becomes zero.
until [ "$2" -eq 0 ]; do set -- "$2" "$(($1%$2))"; done
echo "$1"
}
lcm() { echo "$(( $1 / $(gcd "$1" "$2") * $2 ))"; }
while [ $# -gt 1 ]; do
t="$(lcm "$1" "$2")"
shift 2
set -- "$t" "$@"
done
echo "$1"
try it with:
$ ./script 2 3 4 5 6
afaq
60
가장 큰 입력 및 결과 미만이어야 한다 '또는' (2 ^ 63) -1 쉘로 mkl 마무리 된다.
ES6 스타일
function gcd(...numbers) {
return numbers.reduce((a, b) => b === 0 ? a : gcd(b, a % b));
}
function lcm(...numbers) {
return numbers.reduce((a, b) => Math.abs(a * b) / gcd(a, b));
}
그리고 스칼라 버전:
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
def gcd(nums: Iterable[Int]): Int = nums.reduce(gcd)
def lcm(a: Int, b: Int): Int = if (a == 0 || b == 0) 0 else a * b / gcd(a, b)
def lcm(nums: Iterable[Int]): Int = nums.reduce(lcm)
내가 찾던 최대공약수 스토리지 솔루션 및 lcm and found 는 다음과 같은 요소를 좋은 링크.
https://www.hackerrank.com/challenges/between-two-sets/forum
다음과 같은 코드를 포함하는. 유클리드 호제법 soundmixer. 최대공약수 알고리즘은 아래 링크를 더불어 대해 설명했다.
private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
private static int gcd(int[] input) {
int result = input[0];
for (int i = 1; i < input.length; i++) {
result = gcd(result, input[i]);
}
return result;
}
private static int lcm(int a, int b) {
return a * (b / gcd(a, b));
}
private static int lcm(int[] input) {
int result = input[0];
for (int i = 1; i < input.length; i++) {
result = lcm(result, input[i]);
}
return result;
}