Sunday 24 March 2013

C PROGRAM TO TEST WHETHER A NUMBER IS PRIME OR NOT!!!


I came across a one line formula for testing primeness of a number in Theory of Computation paper. Its of the form...

αp-1 % p ≡1   if p is prime where α € Z+ and p is a number to be checked for its primeness.


PROGRAM:

#include<stdio.h>

int main()
{
    int p,temp;
    printf("enter the number\n");
    scanf("%d",&p);
    
    if(p==1)       printf("number is neither prime nor composite\n");
    if(p==2)       printf("number is prime\n");
    
    temp=pow(2,p-1);    // i've taken alpha as 2
    if(temp%p==1)        printf("%d is prime",p);
    else        printf("%d is not prime",p);

    getch();
    return 0;
}

No comments:

Post a Comment