gpt4 book ai didi

c - 具有执行时间限制的立方体总和

转载 作者:行者123 更新时间:2023-11-30 20:33:07 25 4
gpt4 key购买 nike

如何将代码的执行时间限制为2秒。该代码计算给定数字(输入)是否可以通过至少两种不同的方式表示为两个立方之和。

#include<stdio.h>

int main() {
int n, j, k, int_count;

scanf("%d", &n);

int_count = 0;
for (j=1; j<=n; j++) {
for(k=j+1; k<=n; k++) {

if(j*j*j+k*k*k == n)

int_count++;
}
}
if(int_count >= 2) {

printf("YES");

}
else
printf("NO");

}

最佳答案

也许只使用 time() 或 gettimeofday()。

#include<stdio.h>
#include<time.h>
int main() {
long n, j, k, int_count;
time_t t;

scanf("%d", &n);
t = time(0);
int_count = 0;
for (j = 1; j <= n; j++)
for(k = j+1; k < n; k++) {
if(j*j*j + k*k*k == n)
if(++int_count > 1) {
puts("YES");
return 0;
}
if (time(0) - t >= 2) {
puts("timeout");
return 1;
}
}
puts("NO");
return 0;
}

关于c - 具有执行时间限制的立方体总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46266154/

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