Q:

How to find whether a given number is prime number in C?

belongs to collection: C Programming on Numbers

0

In this exercise, I will discuss only the trial division method for another algorithm

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In the below code to check prime number, we are checking that the given number n is a multiple of any integer between 2 and (n -1) or not. If the given number n is a multiple of any integer between 2 and (n -1), then n will be not a prime number.

#include <stdio.h>
#define PRIME_NUMBER  1
int isPrimeNumber(int number)
{
    int iLoop = 0;
    int iPrimeFlag = 1;
    //check for negative number and one
    if(number <= 1)
    {
        iPrimeFlag = 0;
    }
    else
    {
        for(iLoop = 2; iLoop < number; iLoop++)
        {
            // check prime number
            if((number % iLoop) == 0)
            {
                //update the flag when number is not prime
                iPrimeFlag = 0;
                break;
            }
        }
    }
    return iPrimeFlag;
}
int main()
{
    int iRetValue = 0;
    int number = 0;
    printf("Enter the number : ");
    scanf("%d",&number);
    iRetValue = isPrimeNumber(number);
    //Check for prime number
    if (iRetValue == PRIME_NUMBER)
    {
        printf("\n\n%d is prime number..\n\n", number);
    }
    else
    {
        printf("\n\n%d is not a prime number..\n\n", number);
    }
    return 0;
}

Output:

Enter the number : 2

2 is prime number..

-----------------------------

Enter the number : 10

10 is not a prime number..

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming on Numbers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Optimize way to find an nth Fibonacci number using... >>
<< C Program to Print Odd Numbers in a Given Range...