public static boolean isPrime(int number) { int i; for (i = 2; i <= number; i++) { if(number % 1 == 0) break; } if(number == i) { return false; } else return true; }
15 Replies  556 Views  Last Post: 29 November 2011  10:17 PM
#1
Checking prime numbers
Posted 29 November 2011  12:30 PM
Replies To: Checking prime numbers
#2
Re: Checking prime numbers
Posted 29 November 2011  12:32 PM
double root = Math.sqrt(n); for(int i = 3; i < root; i += 2){ //check to see if n is evenly divisible by i }
This post has been edited by macosxnerd101: 29 November 2011  12:51 PM
Reason for edit:: Set i = 3, not 2
#3
Re: Checking prime numbers
Posted 29 November 2011  12:49 PM
#4
Re: Checking prime numbers
Posted 29 November 2011  12:52 PM
#5
Re: Checking prime numbers
Posted 29 November 2011  12:52 PM
#6
Re: Checking prime numbers
Posted 29 November 2011  12:59 PM
public static boolean isPrime(int number) { int i; double root = Math.sqrt(number); for (i = 3; i < root; i += 2) { if(number % i == 0) { return false; } } return true; }
Also, I noticed that if I add an else return true after the if statement, I get a compile error: missing return statement. I was wondering why I can't do it this way:
public static boolean isPrime(int number) { int i; double root = Math.sqrt(number); for (i = 3; i < root; i += 2) { if(number % i == 0) { return false; } else return true; } }
#7
Re: Checking prime numbers
Posted 29 November 2011  01:01 PM
#9
Re: Checking prime numbers
Posted 29 November 2011  01:02 PM
#11
Re: Checking prime numbers
Posted 29 November 2011  04:35 PM
#12
Re: Checking prime numbers
Posted 29 November 2011  04:48 PM
But if a number is even, you dont even need to check for anything, just return not prime, unless less if two.
#13
Re: Checking prime numbers
Posted 29 November 2011  04:54 PM
public static boolean isPrime(int number) { int i; double root = Math.sqrt(number); for (i = 3; i < root; i += 2) { if(number % i == 0) { return false; } } return true; }
#14
Re: Checking prime numbers
Posted 29 November 2011  05:05 PM
//first in the method if (number%2 == 0 && number > 2) return false; //then you can continue with other issues
And dont forget that 1 is not prime(take care of that also)
#15
Re: Checking prime numbers
Posted 29 November 2011  05:17 PM
smohd, on 29 November 2011  04:05 PM, said:
//first in the method if (number%2 == 0 && number > 2) return false; //then you can continue with other issues
And dont forget that 1 is not prime(take care of that also)
This also did not work for me, so I tried this and it worked:
public static boolean isPrime(int number) { for(int i = 2; i <= number / 2; i++) { if(number % i == 0) { return false; } } return true; }
