Source of 4.2.java


  1: // Computing the sum of the consecutive integers from 1 to n:
  2: long n = 10000; // ten thousand
  3: 
  4: // Algorithm A
  5: long sum = 0;
  6: for (long i = 1; i <= n; i++)
  7:    sum = sum + i;
  8: System.out.println(sum);
  9: 
 10: // Algorithm B
 11: sum = 0;
 12: for (long i = 1; i <= n; i++)
 13: {
 14:    for (long j = 1; j <= i; j++)
 15:       sum = sum + 1;
 16: } // end for
 17: System.out.println(sum);
 18: 
 19: // Algorithm C
 20: sum = n * (n + 1) / 2;
 21: System.out.println(sum);