gpt4 book ai didi

C-给定数的最大质因数

转载 作者:行者123 更新时间:2023-12-02 08:38:19 25 4
gpt4 key购买 nike

我编写了以下代码来计算所提供数字的最大质因数通过标准输入但它需要很长时间才能执行。我怎样才能减少程序的执行时间?

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool is_prime(unsigned long long num)
{
if (num == 0 || num == 1)
return false;
if (num == 2)
return true;
for (unsigned long long j = 2; j < num; j++)
if(num%j==0)
return false;

return true;
}

int main(void)
{
unsigned long long n,i;
printf("enter the number: ");
scanf("%llu",&n);
for(i=n-1;i>1;i--)
if((is_prime(i)) && n%i==0)
break;
printf("%llu\n",i);

return 0;
}

输入的数字是 600851475143。

最佳答案

bool is_prime(unsigned long long num)
{
if (num < 2) return false; /* Reject border cases */

if (num == 2) return true; /* Accept the largest even prime */

if ((num & (~1)) == num) return false; /* Reject all other evens */

unsigned long long limit = sqrt(num) + 1; /* Limit the range of the search */

for (unsigned long long j = 3; j < limit; j += 2) /* Loop through odds only */
if(num % j==0)
return false; /* Reject factors */

return true; /* No factors, hence it is prime */

}

关于C-给定数的最大质因数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19077034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com