That's a coincidence, I've just made this function to find that. Actually it was my Dad, a math lover, who made the logic, i just translated to code. He has coded that a long time ago in his Hp calculator... It looks like it is working :) I have printed all prime numbers from 5 to 1,000,000 with it. And is in portuguese... Well I'll translate the messages here. Also there is no check for negative numbers. Now I will look to the Sieve of Eratosthenes to see how it compares :)
- boolean testaPrimo(double in)
- {
- double i = 3; // double needed for big numbers
- if (in == 3 || in == 2)
- {
- println(in + " Is prime");
- return true;
- }
- if(in % 2 != 0) // if even return quickly
- {
- while(in % i != 0 )
- {
- if(i >= Math.sqrt(in))
- {
- println(in + " It is prime because the last divisor tested " + i + " is bigger than the square root " + (Math.sqrt(in)) + " of the number tested.\n");
- return true;
- }else{
- i+=2;
- }
- }
- println((int)in +" Not prime as is divisible by " + i + "\n");
- return false;
-
- }else
- {
- println(in + " Not prime cause " + in + " is even." + "\n");
- return false;
- }
- }