Your
prime()
function exhibits undefined behavior. If it doesn't find a prime, the final conditional will also be false (becausea
is near thesqrt(n)
, not nearn
), which means you will have no executed return statement. To fix this, Justreturn 1
if you complete the for loop (that is, you find no prime divisors).You want to print an
unsigned long long
. The format string for that is%016llX
.You shift
b
one too many times. Let's assume the last loop of the for loop (computinga + 0
) is prime. You'll write that to the bottom bit, and then move it over one place.
Fixing these errors, we get some code that looks like:
#include <stdio.h>
#include <math.h>
int prime( unsigned long long n ){
int a;
for(a = 2; a<=sqrt((double)n); a++)
if( n%a == 0 )
return 0;
return 1;
}
unsigned long long setPrimeBits( unsigned long long base ){
int a;
unsigned long long b = 0x000000000000000ULL;
for(a = 63; a >= 0; a--) {
b = b << 1;
if(prime(base+a))
b |= 1;
}
return b;
}
int main(){
printf( "%16llX\n", setPrimeBits( 100 ));
}
Which, when run, reports:
[12:54pm][wlynch@watermelon /tmp] ./pr
820A00A08800228A
And, because there seems to be confusion about the left-shifting in other answers, you could write an equivalent setPrimeBits()
that looks like this:
unsigned long long setPrimeBits( unsigned long long base ){
int a;
unsigned long long b = 0x000000000000000ULL;
for(a = 0; a < 64; a++)
if (prime(base+a))
b |= (1ULL << a);
return b;
}