Write an expression (on paper) for the ith term of the sequence. Part of this is deciding if terms go from
0 to
n-1; or
1 to
n; or
0 to
n. Use a calculator or spreadsheet (as suggested by Banfa) to verify this expression. Once you have it on paper, it should be easy to implement in code.
Computing the sum of the terms is trivial:
- sum = 0;
-
for (i=1; i<=n; i++)
-
sum += term(i);
Adjust the starting and ending
i accordingly if your terms don't go from
1 to
n.
FYI: this code snippet presents a concept; don't expect it to compile.
The value of the sequence gets big pretty fast as
n increases. You should do a quick check to make sure your integral type won't overflow. Conversely, it would be a very good idea to determine the smallest value of
n that causes overflow and reject any value greater than or equal to that limit. You should also reject negative
n; and you should reject
n==0 if your terms start at 1. I advise you to get in the habit of validity-checking all user input.
Once you get this working you may want to make it run faster: look for a relationship between
term(i) and
term(i-1). However, don't get ahead of yourself -- you gain nothing by optimizing a program that doesn't work.