C program to make prime numbers or check prime numbers - Online Judge Solution

Latest

It is a free Online judges problems solution list. Here you can find UVA online Judge Solution, URI Online Judge Solution, Code Marshal Online Judge Solution, Spoz Online Judge Problems Solution

Thursday, November 30, 2017

C program to make prime numbers or check prime numbers

C program to make prime numbers or check prime numbers


Problem 1:
Write a  C program to check if the number is prime or not.

Solution:

logic for being a prime number:

C program to make prime numbers or check prime numbers



C Code for check if the number is prime or not:

#include <stdio.h>
int main()
{
   int n, c = 2;
 
   printf("Enter a number to check if it is prime = \n");
   scanf("%d",&n);
 
   for ( c = 2 ; c <= n - 1 ; c++ )
   {
      if ( n%c == 0 )
      {
        printf("%d is not prime.\n", n);
     break;
      }
   }
   if ( c == n )
      printf("%d is prime.\n", n);
 
   return 0;
}


Run Code for check if the number is prime or not in Live [Give input 12 or 19 to check]:




Problem 2:
Write a  C program to generate number of prime numbers.

C code for generate number of prime numbers:

#include <stdio.h>
int main()
{
   int n, i = 3, count, c;
 
   printf("Enter the number of prime numbers required\n");
   scanf("%d",&n);
 
   if ( n >= 1 )
   {
      printf("First %d prime numbers are :\n",n);
      printf("2\n");
   }
 
   for ( count = 2 ; count <= n ;  )
   {
      for ( c = 2 ; c <= i - 1 ; c++ )
      {
         if ( i%c == 0 )
            break;
      }
      if ( c == i )
      {
         printf("%d\n",i);
         count++;
      }
      i++;
   }
 
   return 0;
}



Tags:
C program to make prime numbers or check prime numbers, C program to generate prime, prime number generating, C code,  c programming examples, c codes, prime number algorithm

No comments:

Post a Comment