prime number is only divisible by 1 and itself, we can easily write prime number program in c++, just check number is not divisible by any other numbers except 1 and number itself.

A prime number is a natural number which is greater than 1 and these numbers are only divisible by 1 and itself number. In programming point of view, we check condition number is divisible by other number or not except 1 and number itself. If number is not divisible by other number than that number is prime number.

#include #include void main() { int num,res=0; clrscr(); printf("\nENTER A NUMBER: "); scanf("%d",&num); res=prime(num); if(res==0) printf("\n%d is a prime number",num); else printf("\n%d is not a prime number",num); getch(); } int prime(int n) { int i; for(i=2;i<=n/2;i++) { if(n%i!=0) continue; else return 1; } return 0; }

Super logic.............

ReplyDeletePrime number program in C++

ReplyDeleteprime number is only divisible by 1 and itself,

we can easily write prime number program in c++, just check number is not divisible by any other numbers except 1 and number itself.

Prime number program in C++

ReplyDeleteA prime number is a natural number which is greater than 1 and these numbers are only divisible by 1 and itself number. In programming point of view, we check condition number is divisible by other number or not except 1 and number itself. If number is not divisible by other number than that number is prime number.

can you write the program with using only while loop?

ReplyDeleteYou mean avoid the usage of do-while ??

DeleteThis code is correct ?Prime Number Program in C

ReplyDelete#include

#include

void main()

{

int num,res=0;

clrscr();

printf("\nENTER A NUMBER: ");

scanf("%d",&num);

res=prime(num);

if(res==0)

printf("\n%d is a prime number",num);

else

printf("\n%d is not a prime number",num);

getch();

}

int prime(int n)

{

int i;

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

{

if(n%i!=0)

continue;

else

return 1;

}

return 0;

}