C/C++ by Chris Heath

isPrime() | check_prime.cpp | [back to chrisheath.us ⤶]


isPrime() [back to top]
C function to Check if a Number is Prime

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*** returns 1 if input is prime, 0 if not ***/
int is_prime (int num)
{
    int n;
 
    // avoid loop;  0 or 1 are never prime
    if (num == 0 || num == 1)
        return 0;
 
    // loop through numbers 0..(n/2)+1, trying to
    // divide one into the other with no remainder.
    for (n=2; n < (num/2)+1; n++) {
 
        // if we had no remainder during a revision,
        // input number has a divisor... NOT PRIME!
        if ((num % n) == 0)
          return 0;
    }

 
    // made it through gauntlet...prime!
    return 1;
}
/***
This example will only work with input values of -32767 to 32767 due to the (implied) (signed) int data type. 
To expand the range, just use the other numeric data types where int appears in this code snippet!
For example, unsigned int would double the range by using only positive numbers (0 - 65535). 
Better yet, we can utilize long or unsigned longwhich allows for numbers -2147483647 to 2147483647 and 0 to 4294967295, respectively!
Also, yes, there is the epic long long, but I neglected to mention it due to it not being in many languages...
***/


check_prime.cpp [back to top]
C++ program to check if a number is prime

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// check_prime.cpp
// Author: Chris Heath
// Date: 12/9/2018
// Description: Accepts user input to check if the user entered a prime number.
// Notes: If any text inputted after an integer will be ignored.
// For example: 1234.5678 and 98abc will be interepred as 1234 and 98, respectively.

#include <iostream>
#include <string>
#include <limits>

using namespace std;

int is_prime (unsigned long int num)
{
    unsigned long int n;
    // avoid loop;  0 or 1 are never prime
    if (num == 0 || num == 1)
        return 0;
    // loop through numbers 0..(n/2)+1, trying to
    // divide one into the other with no remainder.
    for (n=2; n < (num/2)+1; n++)
    {
        // if we had no remainder during a revision,
        // input number has a divisor... NOT PRIME!
        if ((num % n) == 0)
          return 0;
    }
    // made it through gauntlet...prime!
    return 1;
}

int main()
{
 unsigned long int i;
 cout<<"Enter an integer to check if it is a prime: ";
 cin>>i;
 while(1)
 {
  if(cin.fail())
  {
   cin.clear();
   cin.ignore(numeric_limits<streamsize>::max(),'\n');
   cout<<"You have entered wrong input.\nPlease try again: 
";
   cin>>i;
  }
  if(!cin.fail())
  break;
 }
 if ( is_prime(i) )
  cout<<"\n"<<i<<" IS PRIME!"<<endl;
 else
  cout<<"\n"<<i<<" is NOT prime."<<endl;
return 0;
}


[back to chrisheath.us ⤶]