Program 5.10: How Much Does the King Owe?

class CountWheat  {

  public static void main (String args[]) {
  
    int i, j, k;

    j = 1;
    k = 0;

    for (i=1; i <= 64; i++) {
      j *= 2;
      k += j;
      System.out.print(k + "\t  ");
      if (i%4 == 0) System.out.println();
    } 
    System.out.println("All done!");

  }

}
Here's the output:

% javac CountWheat.java
% java CountWheat
javac CountWheat.java
java CountWheat
% 2        6           14         30
62         126         254        510
1022       2046        4094       8190
16382      32766       65534      131070
262142     524286      1048574    2097150
4194302    8388606     16777214   33554430
67108862   134217726   268435454  536870910
1073741822 2147483646  -2         -2
-2        -2           -2         -2
-2        -2           -2         -2
-2        -2           -2         -2
-2        -2           -2         -2
-2        -2           -2         -2
-2        -2           -2         -2
-2        -2           -2         -2
-2        -2           -2         -2
All done!
%
What happened? After 2,147,483,646 grains of wheat were counted the next number should have been 6,442,450,938. However an int canšt be larger than 2,147,483,647. The number instead wrapped around into the negative numbers and stayed there.

You can improve your results slightly (but only slightly) by changing the ints to longs. A long is an integer type variable that can hold up to 9,223,372,036,854,775,807. However even that isn't enough to count how much wheat the king owed. To truly calculate the kingšs debt use a double, the largest type of all.


Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home