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 (= 2; i < number; i++)
  {
    if((number%i) ==0) 
      return FALSE;
10    }
11    return TRUE;
12  }
13 

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++)
  {
10      if(is_prime(index) != FALSE){
11        printf("%u,", index);
12      }
13    }
14    printf("\b.");
15    return 0;
16  }
17 
18  Output:
19  Print Prime numbers till #50
20  1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47.
21 

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++)
10    {
11      if(is_prime(index) != FALSE){
12        printf("%u,", index);
13        count--;
14      }
15    }
16    printf("\b.");
17    return 0;
18  }
19  Output:
20  How many prime no to print #10
21  1,2,3,5,7,11,13,17,19,23.
22 

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

signed and unsigned compare, palindrome digits, upper and lower 16bit of 32bit unsigned, Exchange variables, prime number, HCF, LCM, Pascals triangle,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan