First be clear.
What is prime number?
"A prime number is a whole number greater than 1, whose
only two whole-number factors are 1 and itself. "
simply, a number that can be divided by 1 and itself only.
How to start thinking ?
Clearly , every number is divisible by 1. So , our task is to check whether the number has any other divisor except itself or not, and If not , the number is prime number.
Program #1 : Print prime numbers up to n , where n is entered by user .
So we need to check every number falling in the domain 2<=i<=n,
where i is arbitrary number starting from 2 and ending with n itself .
Now,
How to check-
- Consider numbers from 2 to that number.
- Check for divisibility of the number from 2 to the number under consideration by using %(division modulo).
- If there is a divisor apply break!
- Means number may not be prime unless the number under consideration is divisor itself.
- So if the divisor is the considered number .
- The number is prime .
- Print that number.
Now try to follow this steps for building a program and if you are unable to build copy the code given here. The code contains comments for explanation purpose .
How to follow these procedure in c program :C Program : Prime numbers !
#include < stdio.h >
int main()
{
int i,j,n;/*declaration of required variables , i for considering number ,j for checking divisibility and n for user entry.*/
printf("Enter n upto which you want prime number !\n");
scanf("%d",&n);
printf("Required prime numbers are:\n");
for(i=2;i < = n;i++)/*loop for considering number from 2 to n*/
{
for(j=2;j < = i;j++)/*loop for checking divisibility of number*/
{
if(i%j==0)/*the number has divisor , break here*/
break ;
}
if(i==j)/*the divisor is number itself, the number is prime according to definition*/
printf("%d ",i);/*printing the prime number*/
}
}
Thank you very much....these ready made programs help me alot....I like to visit your blog regularly...
ReplyDeletemy pleasure !
Delete