简体   繁体   English

c处理12位数字时的性能问题

[英]Performance issue in c while dealing with 12 digit number

currently i am working on a program. 目前我正在研究一个程序。 program is working perfectly but it has performance issue. 程序运行正常,但存在性能问题。 the code is below. 代码如下。

#include<stdio.h>
int calculate(int temp)
{
    int flag = 0,i = 2,tmp = 0;
    for(i = 2;i < temp;i++)
    {
        if(temp % i == 0)
        {
            return 1;
        }
    }
}
int main()
{
    long int i = 2,j,count = 0,n = 600851475143,flag = 0,prime = 0;
    long int check;
    while(i < n)
    {
        if(n % i == 0)
        {
            check = calculate(i);
            if(check != 1)
            {
                prime = i;
                printf(" Prime  number is : %ld \n", prime);
            }
        }
        i++;
    }
    printf(" Max prime number of %ld is : %ld \n",n,prime);
    return 0;
}

I can't able to get the maximum prime number here. 我在这里无法获得最大素数。 can anyone tell me what should i do it takes too much time what should i do to get output fast? 谁能告诉我该怎么办?我花了太多时间才能快速获得输出?

  1. If you are looking for a maximum prime, why are you starting at 2? 如果您正在寻找最大质数,为什么要从2开始? Begin checking at n and work backwards n开始检查并向后工作

  2. calculate can run faster since you only need to check for a divisor up to sqrt(temp) , if it has a divisor larger than that, it also has a divisor smaller than that. 由于您只需要检查sqrt(temp)以下的除数,因此calculate可以运行得更快,如果除数大于sqrt(temp) ,则它的除数也小于该值。

  3. Your loop increments and decrements can be done in hops of 2. So you'd also halve the range of numbers to check. 循环的增量和减量可以在2跳中完成。因此,您还可以将要检查的数字范围减半。

  4. Calling printf in the middle of a search loop for when the check fails is just a waste of execution speed. 如果检查失败,则在搜索循环的中间调用printf只是在浪费执行速度。 Instead, check for success and break out of the loop. 相反,请检查是否成功,然后跳出循环。

With these modifications in mind (and your code cleaned from a lot of UB): 考虑到这些修改(并且从许多UB中清除了代码):

#include<stdio.h>
int calculate(long int temp)
{
    long int flag = 0,i = 2,tmp = 0;

    if (temp % 2 == 0)
        return 1;

    for(i = 3; i*i <= temp; i+=2)
    {
        if(temp % i == 0)
        {
            return 1;
        }
    }
    return 0;
}

int main(void)
{
    long int j, count = 0, n = 600851475143, i = n, flag = 0, prime = 0;
    long int check;
    while(i > 0)
    {
        if(n % i == 0)
        {
            check = calculate(i);
            if(check)
            {
                prime = i;
                break;
            }
        }
        i-=2;
    }
    printf(" Max prime number of %ld is : %ld \n",n,prime);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM