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++) {
      k += j;
      j *= 2;
      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
1	  3	  7	  15	  
31	  63	  127	  255	  
511	  1023	  2047	  4095	  
8191	  16383	  32767	  65535	  
131071	  262143	  524287	  1048575	  
2097151	  4194303	  8388607	  16777215	  
33554431	  67108863	  134217727	  268435455	  
536870911	  1073741823	  2147483647	  -1	  
-1	  -1	  -1	  -1	  
-1	  -1	  -1	  -1	  
-1	  -1	  -1	  -1	  
-1	  -1	  -1	  -1	  
-1	  -1	  -1	  -1	  
-1	  -1	  -1	  -1	  
-1	  -1	  -1	  -1	  
-1	  -1	  -1	  -1	  
All done!
%
What happened? After 2,147,483,647 grains of wheat were counted the next number should have been 4,294,967,295. 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 quite large enough to count how much wheat the king owed. To accurately calculate the king's debt use a double, the largest type of all.


Copyright 1996, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
This Chapter
Examples
Home