Finding a certain integer

I've been working on this one for a few days and I'm not sure if I'm even in the ball park. Find an integer N such that the sum 1 + 2 + 3 + ... + N is less than the value 31096 and the sum 1 + 2 + 3 + ... + N + (N + 1) is greater than 31096. Print out the value of N. When I run the program nothing happens. This is what I've got so far:

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{

int num1 = 1, num2 = 2, sum = 0;

for (;;)
{
sum+=num1;
num1++;
sum+=num2;
num2++;

if (num1 < 31096 && num2 > 31096)
{
break;
}
}

cout << "The number is " << num1 << endl;
return 0;
}
Well, you're looking for the N such that the sum is below 31096, not the number. For example, the number could be 300, but the sum might be 31096.

edit: hmm, I wasn't actually too far off. A much more clever way would just to be use the summation formula, which would be O(1) rather than O(N).
Last edited on
closed account (D80DSL3A)
You can get real close to the answer by remembering that a sum = (# of terms)*( average value of terms) = N*(N+1)/2 = 31096. This is approximate but very close for large N. If I approximate
sum = N*N/2 then N = sqrt(2*sum). This gives N = sqrt(2*31096) = 249. A check reveals this is very close. I would submit the program I wrote to check this (and to find the value also) but this sounds like a homework problem. Hope the hint helps.
I would agree with Declan. You need to check sum, not numbers. A couple things to look out for:

1) You're probably gonna want to track two sums, ie Sum1 and Sum2. Otherwise you'll run into logic problems since sum can't be less than 31096 and greater than 31096 at the same time.

2) Any particular reason for the for loop? Why not try a while loop with an embedded if statement? The while loop could check Sum1 (ie, to make sure it's less than 31096) and the if statement could check Sum2 (to see if it's greater than 31096).
Topic archived. No new replies allowed.