Program to Check Whether the Number is Prime or Not

Number is Prime or Not

A prime number is a number which can be divided by 1 and itself i.e. a number which can not be divided by any other number other than 1 or itself is a prime number.

Example: 2,3,5,7,11….so on are the prime number as we can see they only have two divisors, 1  and the number itself.


Algorithm

  1. Start
  2. Read a “num” value to check prime or not.
  3. set i=1,div=0.
  4. if i<=num if true go to step 5, else go to step 8.
  5.  Check the condition num%i==0 if true then evaluate step 6, else go to step 7.
  6. set div=div+1
  7.  i=i+1, go to step 4
  8. check div, if div==2 display prime, else display not prime
  9. Stop

Working

  • This program takes a number from user and checks whether the number entered by the user is perfectly divisible by i or not.
  • If true then value of div is incremented else no change the loop continues with the increment in i until i is equal to the entered number.
  • After the loop the value of div is checked and based on that we get whether the number is prime or not.

C++ Code

//C++ Program
//Check Prime or Not
#include<iostream>
using namespace std;
int main()
{
	int i,num,div=0;		//initializing variables
	cout<<"Enter number:";	
	cin>>num;			//user input
	for(i=1;i<=num;i++)		//checking for number of divisor
	{
		if(num%i==0)
		{
			div++;				
		}
	}
	if(div==2)			//no divisors other than 1 and itself
	{
		cout<<num<<" is a prime number";
	}
	else
	{
		cout<<num<<" is not a prime number";
	}
	return 0;

Output

Enter number:31
31 is a prime number

Program to Check Prime Number or not in c.

#include <stdio.h>
int main() {
    int n, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for (i = 2; i <= n / 2; ++i) {

        // condition for non-prime
        if (n % i == 0) {
            flag = 1;
            break;
        }
    }

    if (n == 1) {
        printf("1 is neither prime nor composite.");
    }
    else {
        if (flag == 0)
            printf("%d is a prime number.", n);
        else
            printf("%d is not a prime number.", n);
    }

    return 0;
}

Output

Enter a positive integer: 29
29 is a prime number.

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *