// Calculate all primes upto N, set the boolean to true for all composites
boolean isComposite[] = new boolean[N+1];
// calculate all primes upto N
for(int i=2;i*i<=N;i++){
if(!isComposite[i]){ // if prime
for(int j=i*i;j<=N;j+=i){
isComposite[j] = true;
}
}
}
// Calculate the GCD of 2 no.s using recursive euclidean algorithm
private static long gcd(int a, int b) {
if(a<b){
// swap numbers
a = a^b;
b = b^a;
a = a^b;
}
if(b == 0)
return a;
return gcd(b,a%b);
}
private static long lcm(int a, int b) {
return a*b/gcd(a,b);
}
No comments:
Post a Comment