检查一个数字是否均匀地划分为其他许多人



我有一个编程问题,希望我检查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] | x1 <= i <= n,则lcm(a[1], ..., a[n]) | x

对于这种情况,只需检查lcm(1,2,...,12) | h是否,即h % 27720 == 0


  1. https://en.wikipedia.org/wiki/least_common_multiple

您可以简单地将另一个用于循环中的循环,以摆脱已使用的长期语句。

#include <iostream>
#include <cstring>
using namespace std;
int main(){
    int hex, count = 0;
    int divider = 12;
    for (int n = 1; n <= 30000; n++){
        hex = n * ((2 * n) - 1);
        int subcount = 0;
        for (int i = 1; i <= divider; ++i){
            if (hex % i == 0){
                ++subcount;
                if(subcount == devider){
                     ++count;
                }
            }
        }
    }
    cout << count << endl;
}

最新更新