【问题标题】:How to find a prime no without using my function chk prime as i wish to optimize my algo如何在不使用我的函数 chk prime 的情况下找到素数,因为我希望优化我的算法
【发布时间】:2015-03-25 15:40:04
【问题描述】:
long long int chkPrime(long long int z)
{   
    int i;

       if(z==1)
          return 0;

      if(z==2)
           return 1;

       for(i=2;i<=z/2;i++)
             if(!(z%i))
                     return 0;
    return 1;
}

【问题讨论】:

  • 也许你想在这篇文章中添加一个问题。
  • 是的,您最好将返回类型更改为int 甚至unsigned char,因为它只返回非常小的数字。如果您想将 very 大数字传递给您的函数,您可以使用 unsigned long long 而不是 long long int(如果您的编译器支持它)。功能还可以,我觉得没必要去掉。
  • 您可以通过先剔除偶数 z,然后仅使用偶数 i 进行测试,将执行时间减半。您可以通过仅迭代到 z 的平方根来进一步减少执行时间。

标签: c


【解决方案1】:

如果您想检查某个数字是否绝对是素数,最快(即多项式运行时)确定性算法是AKS-test(Wikipedia) afaik。

如果你想为某个范围创建质数,你应该查看sieving(Wikipedia),或者,我建议从互联网上下载它们作为列表(例如,here 用于前 10000)。

关于筛分的维基百科文章提到了两个很好的概率素性检验,所以我不再提及。然而,该测试仅说明一个数字是否是具有大概率的素数(所谓的可能素数)。

【讨论】:

    【解决方案2】:

    根据我上面的评论,这是一个更有效的功能,尽管 OP 想知道如何“不使用我的功能”

    #include<stdio.h>
    #include<math.h>
    
    int chkPrime(long long int z)
    {   
        long long int i, rootz;
        if (z <= 1)
            return 0;
        if (z == 2)
            return 1;
        if (z % 2 == 0)
            return 0;
        rootz = (long long int)sqrt((double)z);
        for (i=3; i<=rootz; i+=2)
            if (z % i == 0)
                return 0;
        return 1;
    }
    
    int main(void)
    {
        long long int i;
        for (i=0; i<100; i++)
            if (chkPrime(i)) printf("%5lld ", i);
        return 0;
    }
    

    【讨论】:

    • 你不必上 sqrt() 我认为 log2() 就足够了
    • @GRC 如果你想找到 121 的因子,你必须迭代 最多 11,它的平方根,因为 121 没有其他因素。
    • 进入函数前可以检查sqrt()是否为整数
    • @GRC 我已经在函数中了。平方根在转换为long long int 类型后将是一个整数。如果不是,它将被四舍五入。如果它被四舍五入,那不可能是一个尚未检查的因素:这就是迭代到 sqrt 的点。非常大的数字可能会出现错误,因为double 的重要性不如long long int。在这种情况下,long long int 的专用平方根函数并不难,但如果您想发布更好的答案,请这样做。
    • 好吧,这就是我的意思:检查 sqrt((double)z);是一个分数,如果它比继续进入函数,如果不是,那么它不是素数,就像你上面提到的 121。我不是说这是床代码。
    【解决方案3】:

    您可以这样做:

    1. Determine the prime numbers upto sqrt(MaxN) using seive at the beginning of your program.(you need to calculate this only once)
    2. Then each time you call chkPrime do this :
       -- determine sqrt(z)
       -- check if the number can be divided with the primes upto sqrt(z)
       -- if can not be divided then z is a prime number otherwise it is not.
    

    或者,如果您不想在开头生成素数,请执行以下操作:

       1. determine sqrt(z)
       2. check if the number can be divided with 2
       3. if yes then it's not a prime otherwise goto 4
       4. check if the number can be divided with odd numbers from 3 to sqrt(z)
       5. if yes then it's not a prime otherwise it is a prime number
    

    【讨论】:

    • 您的第一个选项不可行,考虑到类型是 long long int,这将是一个庞大的数组。
    • @WeatherVane 你是对的(y)我认为输入不是那么大:(无论如何,总是有选项 2 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 2021-11-01
    • 2013-06-21
    • 2012-05-15
    • 2013-11-10
    相关资源
    最近更新 更多