Last active
August 31, 2019 18:11
-
-
Save sreeprasad/79880f3fd0f3c0eebc92f154c4465f4a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
long countOfNumbers(long N, int[]primeArray) { | |
long sum=0; | |
int totalNumberOfSubsets = 1<<primeArray.length; | |
// loop to generate all subsets from prime array | |
for(int i=1;i<totalNumberOfSubsets;i++) { | |
long count=1; | |
for(int k=0;k<primes.length;k++){ | |
//bit is set then get lcm | |
if((i&(1<<k))!=0) { | |
count = lcm(count, primes[k]); | |
} | |
} | |
// if bit is set i.e number i has odd number of terms, add to total sum | |
// this is because from the inclusion exclusion principle we add odd terms and subtract even | |
if ((1 & Long.bitCount(i))>0) { | |
sum += N/count; | |
} else { | |
// this else part indicates even terms so substract from total sum | |
sum-=N/count; | |
} | |
} | |
return sum; | |
} | |
private long lcm(long a, long b) { | |
return (a/gcd(a,b))*b; | |
} | |
private long gcd(long a, long b) { | |
if(a==0) { | |
return b; | |
} | |
return gcd(b%a,a); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment