Program to check whether the number is prime or not.
Method 1: looping (n-1) times
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1,t=0;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
for(i=1;i<n;i++)
{
if(n%i==0)
t++;
}
if(t==1)
printf("The entered number is prime.");
else
printf("The entered number is not prime.");
getch();
}
Method 2: looping (n-2) times
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=2,t=0;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
t++;
}
if(t==0)
printf("The entered number is prime.");
else
printf("The entered number is not prime.");
getch();
}
Method 3: Best performance looping (n/2+1) times
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=2,t=1;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
for(i=2;i<n/2+1;i++)
{
if(n%i==0)
t++;
}
if(t==1)
printf("The entered number is prime.");
else
printf("The entered number is not prime.");
getch();
}
Method 1: looping (n-1) times
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1,t=0;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
for(i=1;i<n;i++)
{
if(n%i==0)
t++;
}
if(t==1)
printf("The entered number is prime.");
else
printf("The entered number is not prime.");
getch();
}
Method 2: looping (n-2) times
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=2,t=0;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
t++;
}
if(t==0)
printf("The entered number is prime.");
else
printf("The entered number is not prime.");
getch();
}
Method 3: Best performance looping (n/2+1) times
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=2,t=1;
clrscr();
printf("Enter the number: ");
scanf("%d",&n);
for(i=2;i<n/2+1;i++)
{
if(n%i==0)
t++;
}
if(t==1)
printf("The entered number is prime.");
else
printf("The entered number is not prime.");
getch();
}
No comments:
Post a Comment