Menu

Add Topic

C Programming

waiting answer July 12, 2021

Prime Number program in C

Answers
January 07, 2021

Prime numbers are the whole numbers greater than 1 and are divisible by themselves or only by the number. Example: 2, 3, 5, 7...

Program Description: prime number program in c

    #include <stdio.h>
    int main() {
        int integer_number, flag = 0, i; 
        printf("Enter a number to check: ");
        scanf("%d", &integer_number);

        for (i = 2; i <= integer_number / 2; ++i) {
            if (integer_number % i == 0) {
                flag = 1;
                break;
            }
        }

        if (integer_number == 1) {
            printf("one is neither prime nor composite");
        }else {
            if(flag == 0){
                printf("The entered number is prime");
            }else{
                printf("The entered number is not prime");
            }
        }

        return 0;
    }

OUTPUT

Enter a number to check: 5
The entered number is prime

0 0
January 07, 2021

A prime number is a whole number that has only two factors that is 1 and the number itself. I will show you a simple algorithm to check the prime number program in C.

Algorithm

  1. Input a positive integer variable Num
  2. Divide the positive integer variable with (Num-1 to 2)
  3. If Num is not divisible by any value, then the positive integer variable is prime, else not prime
  4. Else not prime.

Implementation

    #include <stdio.h>

    int main() { 
       int prime;
       int i, num;
     
       printf("Enter a number: ");
       scanf("%d", &num);
       
       prime = 1;

       for(i = 2; i < num; i++) {
          if((num % i) == 0) {
             prime = 0;
          }
       }

       if (prime == 1){
           printf("The number is prime");
       }else{
           printf("The number is not prime");
       }
       return 0;
    }

OUTPUT

          Enter a number: 5
          The number is prime    

0 0
July 09, 2021

A prime number is a whole number that is greater than 1 with exactly two factors. That 1 and the number itself. A prime number cannot be divided into groups of equal numbers. For example, 5 cannot be divided into groups of equal numbers. 5 can only be factorized as 1*5 and 5*1.

A prime number can calculate using tgamma function in C under the math.h header file. It works up to 20!

    #include <math.h>
    #include <stdio.h>
      
    int main()
    {
        int num;
        printf("Enter a positive number: ");
        scanf("%d",&num); 
      
        num = tgamma(num + 1);
      
        printf("%d", num);
        return 0;
    }

Output:

         Enter a positive number: 5
         120    

0 0

Please Login to Post the answer

Leave an Answer