Hello! I have some issues regarding my solution for this problem. On my computer it works fine, but I can't get it accepted on submissions either because of a weird TLE error, or because of a runtime error, which I can't seem to understand where it comes from.
Here is the solution explained: For each position in the specified range, I find the greatest power of two which divides the position and then I just get the final element at that position.
#include <stdio.h>
#include <math.h>
int getElementAtPosition(long long n, long long pos, int powLength) {
int powerOfTwo = llround(pow(2, powLength)) / 2;
while (pos % llround(pow(2, powerOfTwo)) != 0) {
powerOfTwo--;
}
return (n / llround(pow(2, powLength - 1 - powerOfTwo))) % 2;
}
int main(void) {
long long n, l, r;
scanf("%64d %64d %64d", &n, &l, &r);
int powLength = 0;
long long nCopy = n;
while (nCopy != 0) {
powLength++;
nCopy /= 2;
}
int count = 0;
for (long long i = l; i <= r; i++) {
count += getElementAtPosition(n, i, powLength);
}
printf("%d", count);
return 0;
}