Download Quick Currency Converter


Prime/Primality test/isprime C/C++

Description:Checks if a number is prime or not; repeat the process until "-1" is input. If a number is not prime, it also shows the first number by which the given number is divided.

Difficulty: Easy

Language: C++

Compiler/IDE: Visual Studio, dev C++ (others will work as well)



View Source

            							
#include<iostream>
using namespace std;

int main()
{
	int n, i;
	while(true)
	{
		cout<<"Enter a number to check primality; -1 to exit...\n";
		cin>>n;

		if (n == -1)
			break;    //exit while

		bool prime = true;

		for (i = 2;i <= n/2; i++)
		{
			if (n % i == 0)
			{
				prime = false;
				break;
			}
		}

		if (prime)
			cout<<"Number is prime\n\n";
		else
			cout<<"Number is not prime; Its first divided by " << i
                       <<endl<<endl;

	}

}


Notes:The project starts by assumming that the number to be checked is prime, and thus it reads "prime = true". It then divides the number by every number starting from 2 and ending at half the number(if its not divisible till its half, its not divisible at all), checking out the remainder after each division. If the remainder is 0 at any division, we find out that the number is NOT prime and hence we can exit, saying that the number is not prime. If remainder has never been 0, we still have "prime = true", and hence we can say that the number is prime.