[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppPrime
The above example excels in clarity, but is not too intelligent. The example below is more elaborate:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppPrime
(C++) Prime, how to check if a number is prime
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; } }
- include <iostream>
- include <cassert>
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
- assert
- bool
- cassert (header file)
- const
- cin, std::cin
- cout, std::cout
- endl, std::endl
- false
- for
- int
- main
- return
- std::cin
- std::cout
- std::endl
- true
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
