我有一个编程问题,希望我检查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个数字)。有任何想法吗?
如果a[i] | x
为1 <= i <= n
,则lcm(a[1], ..., a[n]) | x
对于这种情况,只需检查是否为lcm(1,2,...,12) | h
,即h % 27720 == 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句