【发布时间】:2016-11-02 12:04:16
【问题描述】:
我被要求分解一个数字并以特定方式显示它。
例如:100 = 2^2*5^2
这是我目前使用的没有骰子的 C++ 代码,很遗憾:
#include <stdio.h>
#include <math.h>
//IsPrime indicates whether a given number is or is not prime.
bool IsPrime(long long n)
{
int j = 3;
if (n == 2)
{
return true;
}
else if (n % 2 == 0)
{
return false;
}
else
{
for (j = 3; j <= sqrt(n); j += 2)
{
if (n%j == 0)
{
return false;
}
}
}
return true;
}
int main(void)
{
long long n_orig,n, i=3 , primecount=0;
scanf("%lld", &n_orig);
n = n_orig;
if (n == 1)
{
printf("1");
return 0;
}
if (IsPrime(n))
{
printf("%lld", n);
return 0;
}
if (n % 2 == 0)
{
while (n >= 2 && n % 2 == 0)
{
primecount++;
n = n / 2;
}
if (primecount == 1)
{
printf("2*");
}
else
{
printf("2^%lld*", primecount);
}
}
primecount = 0;
n = n_orig;
while (i <= n/2)
{
if (IsPrime(i))
{
while (n >= i && n % i == 0)
{
primecount++;
n = n / i;
}
}
n = n_orig;
if (primecount == 0)
{
i++;
continue;
}
if (primecount == 1)
{
printf("%lld*", i);
}
else
{
printf("%lld^%lld*", i, primecount);
}
primecount = 0;
i+=2;
}
printf("\b");
return 0;
}
使用此代码,我能够生成一些测试用例,但是当我将答案上传到大概评估代码的网站时,在 7 个测试用例中(我不知道它们到底是什么),我通过 3,fail 3 和 在一个案例中超过时间限制(甚至没有在问题中声明的时间限制)。我真的很感激一些帮助,请对菜鸟友好!
另外,我真的不想知道我的答案是否可以通过某种方式改进,我现在的首要任务是了解为什么我自己的代码不能按预期工作。
P.S : iostream 和 arrays 的使用是不允许的。
提前致谢。
【问题讨论】:
-
您在执行过程中是否使用调试器单步调试过您的代码?
-
1 是素数吗? 0 是素数吗?
-
你多久调用一次 sqrt 函数?
-
@CoryKramer 实际上我有,但当然是相对较小的数字,因为在跟踪大整数时可能需要相当长的时间。令人惊讶的是,我还没有遇到任何问题。
-
使用
j*j <= n而不是j <= sqrt(n)。