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 int sum = 0; 033 for (int i = 1; i <= limit; i++) { 034 sum += i; 035 } 036 return sum; 037 } 038}