Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

Prime Number Checker

/*
	C++ Prime Number Checker program by lolman_ks.
    This logic can be used to build this program in other languages also.
*/
/*
	Logic: Divide the number by all numbers less than half of the number to
    check. If it is divisible by any of them, return False.
*/

#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int number){
	if(number == 1) return false; //1 is neither prime nor composite.
  	else if(number < 1) return false;
  	/*
    	O is the 0th multiple of every number, x * 0 = 0. Therefore 0 is not
        prime.
        Any -ve number is also composite because it has at least 3 factors:
        Itself, 1 and -1.
    */
  	else if(number == 2) return true; //Only even prime number;
  
  	else{
    	for(int i = 0;i <= ceil(number / 2);++i){
        	if(number % i == 0) return false; //Check exact divisibility.
        }
      	return true; 
      	/*
        	Return true if the loop is not broken and the number is not exactly
            divisible by any number.
        */
    }
}

//Implementations of this function.
//Check prime numbers upto a limit.

int main(){
	int limit;
  	cout << "Enter limit: ";cin >> limit;
  
  	for(int i = 0;i <= limit;++i){
		cout << i << ": " << isPrime(i) << endl;
	}
}

/*
	I hope my answers are useful to you, please promote them if they are.
    #lolman_ks.
*/
 
PREVIOUS NEXT
Tagged: #Prime #Number #Checker
ADD COMMENT
Topic
Name
4+9 =