Problem:  Write a function to find whether a given no. is prime or not. Use the same to generate the  prime numbers less than 100.


What is prime number: A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.A natural number greater than 1 that is not prime is called a composite number. for example,11 is prime because he only ways of writing it as a product,1* 5 or 5*1, involve 5 itself.
Source

Source Code:

/*******************************************/

  1. #include <stdio.h>
  2. #include<conio.h>
  3.  
  4. int main()
  5.  {
  6.                //variables declaration
  7.     int i, j, n, isPrime;
  8.  
  9.     // Reads upper limit to print prime.
  10.     printf("Enter number: ");
  11.     scanf("%d", &n);
  12.  
  13.         printf("\n Prime numbers up to %d are: \n", n);
  14.  
  15.     // Finds all Prime numbers between 1 to n.
  16.     for(i=2; i<=n; i++)
  17.                 {
  18.         // Assume that the current number is Prime.
  19.         isPrime = 1;
  20.  
  21.         // Check if the current number i is prime or not.
  22.         for(j=2; j<=i/2; j++)
  23.                               {
  24.            
  25.             if(i%j==0)
  26.                                              {
  27.                 isPrime = 0;
  28.                 break;
  29.             }
  30.         }
  31.  
  32.         /* If the number is prime then print */
  33.         if(isPrime==1)
  34.                               {
  35.         //display the prime number.
  36.             printf(" %d \t", i);
  37.         }
  38.     }
  39.     getch();
  40.    
  41. }



Output:

Enter number: 35

 Prime numbers up to 35 are:

 2       3       5       7       11      13      17      19      23      29

 31


Enter number: 57

 Prime numbers up to 57 are:

 2       3       5       7       11      13      17      19      23      29

 31      37      41      43      47      53


0 comments:

Post a Comment