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

#1 japanir   User is offline

  • jaVanir
  • member icon

Reputation: 1014
  • View blog
  • 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   User is offline

  • Grand Inquisitor
  • member icon

Reputation: 75
  • View blog
  • 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   User is offline

  • Grand Inquisitor
  • member icon

Reputation: 75
  • View blog
  • 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   User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • 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   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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