[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppPrime

(C++) Prime, how to check if a number is prime

  1. include <iostream>
  2. include <cassert>
bool IsPrime(const int x) { for (int i=2; i<x; ++i) { if (x % i == 0) return false; } return true; } int main() { //Check if it works assert(IsPrime(1)==true); assert(IsPrime(2)==true); assert(IsPrime(3)==true); assert(IsPrime(4)==false); assert(IsPrime(5)==true); assert(IsPrime(6)==false); assert(IsPrime(7)==true); assert(IsPrime(8)==false); assert(IsPrime(9)==false); assert(IsPrime(10)==false); assert(IsPrime(11)==true); //Ask the user for a value std::cout << "Please enter a number: "; int anyNumber = -1; std::cin >> anyNumber; const bool isPrime = IsPrime(anyNumber); if (isPrime == true) { std::cout << "The number is prime." << std::endl; } else { std::cout << "The number is not a prime." << std::endl; } }


The above example excels in clarity, but is not too intelligent. The example below is more elaborate:

bool IsPrime(const int x)
{
  //Only positive numbers are prime
  if(x <= 0) { return false; }
  //1 and 2 are prime (although if 1 is prime can be debated)
  if(x < 3) { return true;  }
  //Even numbers are not prime
  if(x % 2 == 0) { return false; }
  const int halfX = x/2;
  for (int i=3; i<halfX; i+=2)
  {
    if (x % i == 0) return false;
  }
  return true;
}


Code links



last edited (March 16, 2007) by bilderbikkel, Number of views: 7264, Current Rev: 4 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Site Management by Lars Hagelin at Kontantkort.se.