Prime numbers are those positive numbers which are only divisible by 1 and the number itself. A simple logic can be written to check this like starting iteration with 2 to (number -1) and inside this we check if number is divisible. If it completes all iterations and found not divisible by any number in the range then it is a prime number.
#define TRUE 1
#define FALSE 0
bool is_prime(unsigned int number)
{
unsigned int i;
for (i = 2; i < number; i++)
{
if((number%i) ==0)
return FALSE;
}
return TRUE;
}
Print all prime numbers in a given range
int main(int argc, char* argv[])
{
unsigned int index;
unsigned int range;
printf("Print Prime numbers till #");
scanf("%u", &range);
for(index = 1; index <= range; index++)
{
if(is_prime(index) != FALSE){
printf("%u,", index);
}
}
printf("\b.");
return 0;
}
Output:
Print Prime numbers till #50
1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47.
Print first n-number of prime numbers
int main(int argc, char* argv[])
{
unsigned int index;
unsigned int count;
printf("\nHow many prime no to print #");
scanf("%u", &count);
for(index = 1; count > 0; index++)
{
if(is_prime(index) != FALSE){
printf("%u,", index);
count--;
}
}
printf("\b.");
return 0;
}
Output:
How many prime no to print #10
1,2,3,5,7,11,13,17,19,23.
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Learn on Youtube
‹
#
›