判断是否是素数

Three methods to check is prime, the later, the better.

#include <stdio.h>
#include <math.h>

int isPrime(int n)
{
    int i;
    for( i = 2; i < n; i++)
        if(n % i == 0)
            return 0;
    return 1;
}

int isPrime2(int n)
{
    int i;
    for( i = 2; i <= sqrt(n); i++)
        if(n % i == 0)
            return 0;
    return 1;
}

int isPrime3(int n)
{
    int i;
    if(n == 1 || n == 2) 
        return 1;

    if(n % 2 == 0) 
        return 0;

    // Only need to check the odd ones.
    for( i = 3; i <= sqrt(n); i += 2)
        if(n % i == 0)
            return 0;
    return 1;
}

 

posted @ 2013-10-26 19:11  alexeyqian  阅读(126)  评论(0编辑  收藏  举报