001package de.hdm_stuttgart.sd1.sum; 002 003/** 004 * Summing up integer values. 005 * 006 */ 007public class Summing { 008 009 /** 010 * @param args unused 011 */ 012 public static void main(String[] args) { 013 // Simple tests 014 System.out.println("1 + 2 + 3" + "=" + getSum(3)); 015 System.out.println("1 + 2 + ... + 150" + "=" + getSum(150)); 016 017 018 long start = System.nanoTime(); 019 System.out.println("1 + 2 + ... + 65535" + "=" + getSum(65535)); 020 long end = System.nanoTime(); 021 System.out.println("Elapsed time: " + (end - start) + " nanoseconds"); 022 } 023 024 /** 025 * Summing up all integers starting from 0 up to and including a given limit 026 * Example: Let the limit be 5, then the result is 1 + 2 + 3 + 4 + 5 027 * 028 * @param limit The last number to include into the computed sum 029 * @return The sum of 1 + 2 + ... + limit 030 */ 031 public static long getSum(int limit) { 032 if (limit < 0) { 033 return 0; 034 } else if (0 == limit % 2){ // even limit, divide by 2 035 return limit / 2 * (limit + 1); // Avoiding arithmetic overflow 036 } else { // uneven limit, divide (limit + 1 ) by 2 037 return (limit + 1) / 2 * limit; // Avoiding arithmetic overflow 038 } 039 } 040}