获取低于特定数字的所有礼貌数字

Getting all Polite numbers below a certain number

我正在尝试编写一个 C++ 程序来显示所有低于特定数字的礼貌数字。因此,例如,如果有人要输入 6,那么我想打印出 3、5、6。如果要输入数字 9,我想打印出 3,5,6,7,9。

我已经完成了两个 for 循环。我只是不知道如何测试所有连续的数字组合,以获得礼貌的数字。

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;
int main()
{
cout << "Welcome to the polite numbers program." << endl;

int upValue;
int num1, num2;

cout << "What is the upper value? "; //Ask user for upper limit
cin >> upValue; //Stores user input into upValue

while (upValue < 1) //Validate user input of upper limit
{
    cout << "What is the upper value? (must be an integer > 0) ";
    cin >> upValue;
}

for (num1 = 1; num1 <= upValue; num1++) { //Looping from 1 to upper variable


for (num2 = num1 + 1; num2 <= upValue; num2++) { //Looping from 2 to upper

//Something goes here to get all polite numbers below a certain number.
}
}

return 0;
}

您可以将其分解为两个较小的问题。

这是一个实施示例。可能有更有效的方法来做到这一点,但这应该让您了解需要做什么。

// calculate the sum of all integers between "start" and "end" inclusive.
// hint: the sum of integers between 1 and n is "n(n + 1) / 2".
int sum_between(int start, int end)
{
    return (end * (end + 1) - start * (start - 1)) / 2;
}

// determine if a number polite
bool number_is_polite(int num)
{
    // a little shortcut, we know any number less than 3
    // cannot be polite
    if (num <= 2)
        return false;

    // get the starting point, which must be at least 2 away
    // from the target number
    for (int start = 1; start <= num - 2; start++)
    {
        // get the ending point, which must be at least 1 away
        for (int end = start + 1; end <= num - 1; end++)
        {
            // return true if the sum of integers between start/end
            // inclusive is equal to the target number
            if (sum_between(start, end) == num)
                return true;
        }
    }

    // we searched all consecutive integer subsets but nothing
    // seemed to sum to the target number
    return false;
}

现在我们可以完成您的代码了:

#include <iostream>
#include <iomanip>
#include <cmath>

// < insert functions from above >

using namespace std;
int main()
{
    cout << "Welcome to the polite numbers program." << endl;

    int upValue;

    cout << "What is the upper value? "; //Ask user for upper limit
    cin >> upValue; //Stores user input into upValue

    while (upValue < 1) //Validate user input of upper limit
    {
        cout << "What is the upper value? (must be an integer > 0) ";
        cin >> upValue;
    }

    for (int i = 2; i <= upValue; i++)
    {
        if (number_is_polite(i))
            cout << i << " ";
    }

    cout << endl;
}