Pages - Menu

Monday 15 October 2012

Checking if a number is prime or not in C

A number is a prime number if it has no positive divisors except for 1 and itself. 

The function below evaluates whether the number received as argument in the function call is a prime number or not.

#include<stdio.h>
#include<conio.h>

int Prime(int number);

int main(void)
{
    int number = 0, prime = -1;
    printf("\n Enter the number: ");
    scanf("%d",&number);
    prime = Prime(number);
    if (prime == 0)
    {
        printf("\n\t\tThis number is not prime.");
    }
    else if (prime == 1)
    {
        printf("\n\t\tThis number is prime.");
    }
    getch();
    return 0;
} 
Example1: checking if a given number is prime or not
int main(void)
{
    int number = 0, prime = -1;
    printf("\n Enter the number: ");
    scanf("%d",&number);
    prime = Prime(number);
    if (prime == 0)
    {
        printf("\n\t\tThis number is not prime.");
    }
    else if (prime == 1)
    {
        printf("\n\t\tThis number is prime.");
    }
    getch();
    return 0;
} 
Output:  

Example2: displaying the first n prime numbers
#include<stdio.h>
#include<conio.h>

int Prime(int number);

int main(void)
{
    int n = 0, counter = 0, i = 1, prime = -1;
    printf("\n Enter how many prime numbers to be displayed: ");
    scanf("%d",&n);
    printf("\n\n\tThe first %d prime numbers are: ",n);
    while (counter < n)
    {
        prime = Prime(i);
        if (prime == 1)
        {
            printf("%d ",i);
            counter++;
        }
        i++;
    }
    getch();
    return 0;
}
Output:   

Example3: displaying all the prime numbers in a given range
#include<stdio.h>
#include<conio.h>

int Prime(int number);

int main(void)
{
    int a = 0, b = 0, i = 0, prime = -1, ok = 0;
    printf("\n Enter the minimum range: ");
    scanf("%d",&a);
    printf(" Enter the maximum range: ");
    scanf("%d",&b);
    for (i=a; i<=b; i++)
    {
        prime=Prime(i);
        if (prime == 1)
        {
            if (ok == 0)
            {
                printf("\n\tThe prime numbers in the given range are: ");
            }
            printf("%d ",i);
            ok++;
        }
    }
    if (ok == 0)
    {
        printf("\n\tThere are no prime numbers in the given range.");
    }
    getch();
    return 0;
} 
Output:   

No comments:

Post a Comment