/* Programmer: Bill Marion Date: 1/23/06 Modified: 2/16/06 */ /* Import the simple standard I/O classes developed by Prof. Greg Hume. */ import hsa.*; /* Given n >= 1 stones in a pile, split the pile into two smaller piles. Continue to split each pile into two smaller piles until there are n piles of size one. At each splitting compute the product of the size of the two smaller piles. Once there are n piles sum all the products computed. The result will always be the same no matter how each of the piles is split into two smaller piles. The sum of products is a function of n. (Rosen, 2003; Tanton, 2004) */ /* This computational solution generates a recursive process and splits the piles randomly into k and n-k piles until there are n piles of size 1. A runing total of the sum of products is computed. */ class PilesOfStones { static void stones(int numStones) { int sum = 0; sum = stonesSumOfProducts(sum, numStones); Stdout.println(); Stdout.print("Given "); Stdout.print(numStones); Stdout.print(" stones in a pile, the sum of products is: "); Stdout.println(sum); Stdout.println(); } // end stones static int stonesSumOfProducts(int sum, int numStones) { int sizePileOne = 1 + (int) (Math.random() * (numStones - 1)); int sizePileTwo = numStones - sizePileOne; sum = sum + sizePileOne * sizePileTwo; if (sizePileOne != 1) sum = stonesSumOfProducts(sum,sizePileOne); if (sizePileTwo != 1) sum = stonesSumOfProducts(sum,sizePileTwo); return sum; } // end stonesSumOfProducts static public void main(String[] args) { Stdout.println(); Stdout.println("Enter the number of stones in the pile-- enter 0 to stop"); int numStones = Stdin.readInt(); while (numStones >= 1) { if (numStones == 1) { Stdout.println(); Stdout.print("Given "); Stdout.print(numStones); Stdout.print(" stone in a pile, the sum of products is: "); Stdout.println(numStones - 1); Stdout.println(); } else stones(numStones); Stdout.print("Enter the number of stones in the pile-- enter 0"); Stdout.println(" to stop"); numStones = Stdin.readInt(); } Stdout.println(); } // end main } // end PilesOfStones