# Check If a number is prime

Page 1 of 1

## 4 Replies - 2618 Views - Last Post: 22 November 2011 - 12:45 PM

### #1 japanir

• jaVanir

Reputation: 1014
• Posts: 3,025
• Joined: 20-August 09

# Check If a number is prime

Posted 24 November 2009 - 05:37 AM

Description: This code snippet gets a number and returns true if the number is prime. else, returns false if it is not prime.
```public boolean isPrime(int number)
{
for(int i = 2; i < (number / 2); i++)
{
if(number % i == 0)
return false;
}
return true;
}
```

Is This A Good Question/Topic? 0

## Replies To: Check If a number is prime

### #2 zim1985

• Grand Inquisitor

Reputation: 75
• Posts: 568
• Joined: 19-February 10

## Re: Check If a number is prime

Posted 24 February 2010 - 09:02 PM

Actually, in the 'for' loop, it should be: i <= (number / 2) Otherwise you get 4 as a prime number.
Was This Post Helpful? 0

### #3 zim1985

• Grand Inquisitor

Reputation: 75
• Posts: 568
• Joined: 19-February 10

## Re: Check If a number is prime

Posted 03 March 2010 - 06:16 PM

should be <= number/2
Was This Post Helpful? 0

### #4 alexz003

• D.I.C Head

Reputation: 4
• Posts: 78
• Joined: 08-May 10

## Re: Check If a number is prime

Posted 04 May 2011 - 04:56 PM

4 returns true when it should return false.
Was This Post Helpful? 0

### #5 csm23

• New D.I.C Head

Reputation: 0
• Posts: 6
• Joined: 18-July 10

## Re: Check If a number is prime

Posted 22 November 2011 - 12:45 PM

How it is now the comparison should less or equal <=. Also to make it even faster do the square root of the number instead of dividing by two, do the square root of the number outside the for loop and set it to a variable.
Was This Post Helpful? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }