I have a problem counting one bits in a large number ranges.
So I have to count one bits in a eq number range from 1 to 1000 which is 4938.
public static long countRangeOneBits(long n){
long t = 0;
for (long i = 1; i <= n; i++) {
long x = i;
while (x > 0) {
t += x%2;
x /= 2;
}
}
return t;
}
Ok this works fine, but I need to calculate range 1..10^16. First of all java won't count that big numbers, at least with long data type. Do I have any other options or do you guys have any tips on how I should approach this problem.
| From 1 To | Total |
| 1 | 1 |
| 10 | 14 |
| 100 | 319 |
| 1000 | 4938 |
| 10000 | 64613 |
| 100000 | 815030 |
| 1000000 | 9884999 |
| 10000000 | 114434632 |
| 100000000 | 1314447116 |
| 1000000000 | 14846928141 |
| 100000000000000 | 2306412649693200 |
| 1000000000000000 |24784747400675300 |
BigInteger, you can represent any whole number with that (As long as you have enough memory...).