Skip to content

Instantly share code, notes, and snippets.

@bittib
Last active December 9, 2016 06:52
Show Gist options
  • Save bittib/5906858 to your computer and use it in GitHub Desktop.
Save bittib/5906858 to your computer and use it in GitHub Desktop.
Project Euler Problem 5 本题求的是小于某个数的所有数集合的LCM,比较快的做法参考维基百科 利用整数的唯一分解定理,还可以用质因子分解法。将每个整数进行质因数分解。对每个质数,在质因数分解的表达式中寻找次数最高的乘幂,最后将所有这些质数乘幂相乘就可以得到最小公倍数。
public static int solve(int N){
int[] primes = new int[N];
int cnt = 0;
boolean[] isp = new boolean[N+1];
Arrays.fill(isp, true);
isp[0] = false;
isp[1] = false;
for (int i=2; i<=N; i++){
if (isp[i]){
for (int j = i * i ; j <=N; j+=i){
isp[j] = false;
}
primes[cnt++] = i;
}
}
int product = 1;
for (int i = 0; i<cnt; i++){
int j = primes[i];
do {
product *= primes[i];
j *= primes[i];
}while (j <=N);
}
return product;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment