I am currently working on Project Euler and thought that it might be more interesting (and a better learning experience) if don't just brute force all of the questions. On question 3 it asks for prime factors of a number and my solution will be to factor the number (using another factoring algorithm) and then test the factors for primality. I came up with this code for a Miller-Rabin Primality test (after thoroughly researching primality test) and it returns true for all the composite odd number I have put in. Can anybody help me to figure out why? I thought I had coded the algorithm correctly.
public static boolean isPrime(long num)
{
if(num % 2 == 0)
return false;
else
{
double d;
int r=0;
while((num-1) % Math.pow(2,r+1) == 0)
r++;
d = (num-1) % Math.pow(2,r);
int[] a = {2,3,5,7,11,13,17,23,31,62,73,1662803};
boolean primality = true;
for(int k = 0; k < a.length; k++)
{
if((Math.pow(a[k],d)-1) % num != 0)
{
for(int s = 0; s < r-1; s++)
{
if((Math.pow(a[k],Math.pow(2,s)*d)+1) % num != 0)
primality = false;
}
}
}
return primality;
}
Math.pow(a[k],d)-1) % num
-- i'd say your doubles are way over the range where they can represent every integer in that range. – Menorahwhile(num % Math.pow(2,r+1) == 0)
bewhile((num-1) % Math.pow(2,r+1) == 0)
or better still (for my eyes)while((num-1) % (1<<r+1) == 0)
And thend = ((num-1) % (1<<r));
– Adelaideadelaja