Prime number
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. It means a prime number is only divisible by 1 and itself, and it start from 2. The smallest prime number is 2.
**************************************** Prime Number *****************************************/ #include< stdio.h> #include< conio.h> void main() { int i,no; clrscr(); printf("Enter any number: "); scanf("%d",&no); if(no==1) { printf("Smallest Prime number is 2"); } for(i=2;i< no;i++) { if(no%i==0) { printf("Not Prime number"); break; } } if(no==i) { printf("Prime number"); } getch(); }
Output
Enter any number: 10 Not Prime Number
Program Explanation
First enter any number if this number is 1 then show message "Smallest Prime number is 2".
for(i=2;i< no;i++) { if(no%i==0) { printf("Not Prime number"); break; } }
In above code we first perform for loop. First initilize i=2, because Every number is divisible by 1 so we start dividing given number from 2, then check condition "i" is less than number (i< no), and increment value of i (i++). Here "if(no%i==0)" is perform like : no%2==0, no%30=0, no%4==0, no%5==0, no%6==0, no%7==0,....... because every time value of i is increment until value of i is less than given number. If reminder is zero then print "Not Prime number" and control goes outside from for loop due to break keyword.
Note:break is only used within loops (for, while, etc) and switch case.
if(no==i) { printf("Prime number"); }
Here if value of i is equal to Given number then print "Prime number", In this code "i" have same value equal to given number because for loop conditon is "i < no" at that time it false when i==no. So this time "i" have same value to given number. And prime number is divisible by 1 and itself, So here we check no==i.
Print next Prime number
When we enter any number this code will print next Prime number.
Example: Suppose we enter 5 then next prime number is 7.
Example: Suppose we enter 5 then next prime number is 7.
/*********************************************** Next Prime number ************************************************/ #include< stdio.h> #include< conio.h> void main() { int i,j=2,num; clrscr(); printf("Enter any number: "); scanf("%d",&num); printf("Next Prime number: "); for(i=num+1;i< 3000;i++) { for(j=2;j< i;j++) { if(i %j==0) { break; } // if } // for if(i==j || i==1) { printf("%d\t",i); break; } // if } // outer for getch(); }
Output
Enter any number: 10 Next Prime Number 11
No comments:
Post a Comment