|
How much wheat did the king need? Let's try to calculate it. Although we won't use physical wheat, we will soon find ourselves in the same dire straits as the king. Remember that a chessboard has 64 squares.
class CountWheat { public static void main (String args[]) { int i, j, k; j = 1; k = 0; for (i=1; i <= 64; i++) { k += j; System.out.println(k); j *= 2; } System.out.println("All done!); } } We can improve our results slightly (but only slightly) by changing our ints to longs like so:
class CountWheat { public static void main (String args[]) { long i, j, k; j = 1; k = 0; for (i=1; i <= 64; i++) { k += j; System.out.println(k); j *= 2; } System.out.println("All done!); } } 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. Let's try using a double instead, the largest type of all.
class CountWheat { public static void main (String args[]) { int i; double j, k; j = 1.0; k = 0.0; for (i=1; i <= 64; i++) { k += j; System.out.println(k); j *= 2; } System.out.println("All done!); } } A double can hold a number as large as 1.79769313486231570e+308. That turns out to be large enough to count the king's debt which comes to 1.84467e+019 grains of wheat, give or take a few billion grains. That's a lot of wheat.
Exercises
- Would a float be big enough to count how many grains of wheat the king owes?
- Why isn't there a ** or a // operator?
|