以下是我的代码,我尝试使用BigInteger inn Java计算从100到100的所有数字的LCM。但是它没有提供任何答案。

import java.math.BigInteger;

public class CommonOneToHundred {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BigInteger res =new BigInteger("1");
        int i = 2;
        while(i<=100){
        res = lcm(res,BigInteger.valueOf(i));
        i++;
        }
        System.out.println(res);
    }
       static BigInteger lcm(BigInteger x, BigInteger y)
        {
            BigInteger a;
            //a = (x > y) ? x : y; // a is greater number
            a = y;
            while(true)
            {
                if(a.divide(x).equals(0) &&  a.divide(y).equals(0))
                    return a;
                a = a.add(BigInteger.ONE);
            }
        }

}

最佳答案

为什么不将所有质数的最高幂相乘直到100。这是我在python中的代码。

primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
ans = 1
for prime in primes:
  power = 0
  tmp = 1
  while tmp <= 100:
    tmp = tmp*prime
    power += 1
  ans = ans * prime**(power-1)

print ans

答案是69720375229712477164533808935312303556800

09-09 23:14
查看更多