大值的时限超出错误

问题描述 投票:-1回答:1

我有x和k,其中x是数A的因数,k是A素数的数。给定x和k,我必须找出这样的A是否存在。例如

INPUT : 4 2 
OUTPUT : 1

由于6是具有4个因数1、2、3、6的数,其中2是质数(2,3)。还假定x和k可以具有1到10 ^ 9之间的任何值。这是我的相同代码:

long long int x, k;
scanf("%lld%lld", &x, &k);

int ans = 0;

bool stop = false;

for(long long int numbers=1; numbers<pow(10, 9) && !stop; numbers++)
{
    long long int noOfFactors = 0, noOfPrimes = 0;
    for(long long int a=1; a<=numbers && !stop; a++)
    {
        if(numbers%a == 0)
        {
            noOfFactors += 1;
            if((isprime(a)) == 1)
            {
                noOfPrimes += 1;
            }
         }
     }
     if(noOfFactors == x && noOfPrimes == k )
     {
         ans = 1;
         stop = true;
     }
     else ans = 0;
}   
printf("%d\n", ans);

如果x为质数,则isprime(x)返回1,否则为0。

但是在运行程序时,它显示TLE错误。谁能帮助我优化该算法,或者如果存在其他方法,您可以向我解释一下吗?在优化此算法或使用其他方法方面的任何帮助将不胜感激。

c factors largenumber
1个回答
0
投票

所以让我总结一下我对以上的评论:

  1. pow(10, 9)存储在变量中,因此您不必在每次for循环进行下一次迭代时都重新计算它。
  2. 您可以将primeNum的检查减少到仅正方形,这是有道理的,但如果您不舒服,请查看此question或维基百科
  3. 如果检查了一个数字不是素数,请确保您不会在程序执行时再次计算该数字,因为检查素数,特别是当一个数字很大时,检查是很耗时的。
© www.soinside.com 2019 - 2024. All rights reserved.