Tuesday, July 19, 2011

How to write an algorithm in c program for prime number or not?

The algo may be as follows:

STEP1: Take input from user.

STEP2: Check whether the number has any divisor other than 1 and the number itself.

STEP3: If there is any divisor other than 1 or that number itself, then

STEP3.1:Consider the number as NOT PRIME

STEP3.2: Else consider the number as a PRIME NUMBER.

Here is the C program:

#include
#include
void main()
{
int number,i,flag=1;

printf("Enter a number to check whether it is a PRIME NUMBER or not:");
scanf("%d",&number);
for(i=2;i<=number/2;i++)
{
if((number%i)==0)
{
flag=0;
break;
}
}
if(flag==0)
printf("This is not a prime number.");
else
printf("This is a prime number.");
getch();
}

No comments: