C Program to Check Whether a Number is Prime or Not
Here is a simple understanding about prime number ,what is prime number ,how can we find prime number in easy way and how to code for finding prime number in c.
let's first see what is prime number:
..Prime Number : Any number which is only divisible by 1 and itself ,is defined as prime number .We can say the prime number have only two factors i.e 1 and itself.
Ex. - 2,3,,5,7,11.......etc.
Only 2 is the number which is prime as well as even number .
Method to find Number is prime or not :
- step 1:- find the all the factors of the given number . Ex. we have two numbers 91 and 17 ,now find the factors factors of 91 are 1,7,13,91 and that of 17 are 1 & 17.
- step 2 : Check the number of factors of the given number In the above example we have taken there are 4 factors in case of 91 whereas only 2 factors in case of 17.
- step 3 : If the number of factors are more than 2 then it is not a prime number and if it has only two factors it is prime number . so in the above example 91 is not a prime number whereas 17 is prime number.
43, 23, 56, 89, 103, 11, 71, 28, 9, 98, 203, 345, 7, 93, 107, 67, 83.
Well, now we will see how to code these concept through programming language .....
1. #include<stdio.h>
2. int main()
3. {
4. int a,flag=0;
5. printf("Enter any number:");
6. scanf("%d",&a);
7. for(int i=2;i<a;i++)
8. {
9. if(a%i==0)
10. {
11. printf("Number is not a prime ");
12. flag=1;
13. break;
14. }
15. }
16. if(flag==0)
17. {
18. printf("Number is a prime ");
19. }
20. return 0;
21. }
Execution process :
First cursor go to header file and then main function will call. Here we take input as a number
from user ,now control check the factors of that number if any of the number between 2 to given
number divide that number so it return flag =1 then break statement will execute and control will
stop executing further .
If non of the number (between 2 and given number i.e i) is such that if(a%i==0) so control move
out and second if condition will execute .Since flag!=1 then it will remain 0 and that's why if condition will execute .
First cursor go to header file and then main function will call. Here we take input as a number
from user ,now control check the factors of that number if any of the number between 2 to given
number divide that number so it return flag =1 then break statement will execute and control will
stop executing further .
If non of the number (between 2 and given number i.e i) is such that if(a%i==0) so control move
out and second if condition will execute .Since flag!=1 then it will remain 0 and that's why if condition will execute .
No comments:
Post a Comment
If you have any doubt don't hesitate to write in comment section.I will always answer your doubt.