Ming-ming is a diligent student who loves counting. One day, his mother asked him to start counting from N. The next number would be N + 1, and then the next one would be N + 2, and so on. His mother wants to know how many numbers Mingming needs to count until the sum of all the numbers he counted exceeds M. Please help Mingming's mother.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
The input ends with EOF. Each set of test data consists of two numbers, N and M, where the difference M – N will not exceed 10^5. | The output should indicate how many numbers Mingming needs to count until the sum of all the numbers he counted exceeds M. |
1 5 5 10 100 1000 | 3 2 10 |
Thought Process
Assuming N + (N+1) + (N+2) + … + (N+K) ≥ M, use a for loop to sum all the numbers from N to N+K, where the default value of K is 1. Increase K by 1 each time the loop ends, with the termination condition set to when the sum is greater than or equal to M. Set a variable to store the sum of the numbers, initially set to N, and add N+K to it each time the loop runs. Finally, output K, which represents how many times the for loop ran.
Sample Code-ZeroJudge A215: Ming-ming Loves Counting
#include <iostream>
using namespace std;
int main() {
int N, M;
while (cin >> N >> M)
{
int sum = N;
int K = 0;
for (K = 1; sum <= M; K++)
{
sum += N+K;
}
cout << K << endl;
}
}
//ZeroJudge A215
//Dr. SeanXD