Write a c program to find prime numbers






Write a program to find prime numbers in c programming language. Source code:


#include<stdio.h>
#include<math.h>

int main(){


  int num,i,count=0;

  printf("\nEnter any integer number :");
  scanf("%d",&num);

  for(i=2;i<=sqrt(num/2);i++){
        if(num%i==0){
           count++;
           break; //to exit from for loop
        }
  }

  if(count==0)
        printf("%d is a prime number",num);
  else
        printf("%d is not a prime number",num);

  return 0;
}




7 comments:

vikash said...

instead of incrementing i in the for loop to n/2 times ,, it shud be incrementd to square root of n times.


which will increase the efficiency of code to great extent.

Priyanka kumari said...

Hi Vikash,

Thanks a lot!!

Anonymous said...

This program logic is not correct when we input 4 it will also give prime but it was not prime.

Unknown said...

if u also give a discription for this program with output it is better to understand the program

Vivek Mishra said...

#include
#include
void main()
{
int a,i;
clrscr();
printf("Enter the Number-------->");
scanf("%d",&a);
for(i=2;i%d is Prime",a);
else
printf("The number ---->%d is not Prime",a);
getch();
}


Enter the Number-------->5
The number ---->5 is Prime
Enter the Number-------->9
The number ---->9 is not Prime

Unknown said...

#include

main()
{

int n, c = 2,count;

printf("Enter a number to check if it is prime\n");
scanf("%d",&n);

for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n%c == 0 )
{
printf("%d is not prime.\n", n);
break;
}
}
if ( c == n )
{
printf("%d is prime.\n", n);

}


return 0;

}

Unknown said...

why sqrt(num/2) is used..? why not sqrt(num)..? :-(