Question (in Chinese): http://ac.jobdu.com/problem.php?pid=1506

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.

1 2 3 4 5 6 | Input: 3 5 Output: 6 15 |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | /*---------------------------------------------------------------- * Author: Sheng Yu - codesays.com * Written: 09/13/2014 * Last updated: 09/13/2014 * * Filename: Accumulate.java * Compilation: javac Accumulate.java * Execution: java Accumulate * JDK Used: 1.7 *----------------------------------------------------------------*/ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; /** * 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. * @author Sheng Yu codesays.com */ public class Accumulate { private static long total = 0; /** * Reset the sum of numbers to zero. */ public static void init() { total = 0; } /** * @return the stored sum value. */ public static long getSum() { return total; } /** * Compute the sum without condition statement and *, /. * @param n the end number to compute the sum. * @return useless. Help to terminate the recursion. */ public static boolean sum(int n) { total += n; // Use the short-circuit evaluation feature. // http://en.wikipedia.org/wiki/Short-circuit_evaluation return (n == 1) || sum(n - 1); } /** * Stub for test. * @param args the command line arguments. * @throws IOException when input gets error. */ public static void main(String[] args) throws IOException { StreamTokenizer st = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); int n = 0; while (st.nextToken() != StreamTokenizer.TT_EOF) { n = (int) st.nval; init(); sum(n); System.out.println(getSum()); } } } |