【发布时间】:2016-12-13 06:15:41
【问题描述】:
我有一个编程问题,要我检查 30,000 个六边形数字(由公式 H(n) = n(2n-1) 给出),其中有多少可以被数字 1 到 12 整除。
我的代码如下:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int hex, count = 0;
for (int n = 1; n <= 30000; n++)
{
hex = n * ((2 * n) - 1);
if (hex % 1 == 0 && hex % 2 == 0 && hex % 3 == 0 && hex % 4 == 0 && hex % 5 == 0 && hex % 6 == 0 && hex % 7 == 0 && hex % 8 == 0 && hex % 9 == 0 && hex % 10 == 0 && hex % 11 == 0 && hex % 12 == 0)
{
count++;
}
}
cout << count << endl;
}
现在我知道我现在在 if 语句中的检查效率非常低,所以我想知道是否有更简单的方法来检查数字?我尝试使用 for 循环,但无法让它工作(因为它一次只检查 1 个数字)。有什么想法吗?
【问题讨论】:
-
提示:如果一个数字被 12 整除,那么它必须也被 2、3、4 和 6 整除。
-
也可以将
hex % 2 == 0替换为!(hex % 2)等 -
hex % 1 == 0???真的吗?是不是类似于0 == 0? -
using namespace std;然后声明变量hex和count是一个等待完成的曼哈顿计划。 -
我明白你在说什么 VolAnd,放置 %1 是不必要的,感谢您的建议。还要感谢 tkausl,它确实缩短了很多。
标签: c++ if-statement for-loop main iostream