Solution to Accumulate from Jobdu

12 Sep

Question (in Chinese):

Question Name: Accumulate

Question Description: Compute the sum of integers from 1 to n without condition statement like “if”, “while”, “for”, “else”, “switch”, “case” and “? :”. And no multiplication or division is allowed.

Input: the input might contain multiple test cases. One single line is a test case. Each line contain one integers N (1 <= N <= 100000). If it reach the EOF of stdin, quite the program.

Output: print the sum of integers from 1 to N.

The are lots of different solutions. I tried the 1/N solution with try and catch. But it cannot pass the last test. Another common solution is use the short-circuit evaluation feature.

Leave a Reply

Your email address will not be published. Required fields are marked *