// Solution to "PollyNomials" by Bob Roos import java.io.*; import java.util.*; public class Polly { public static BufferedReader in; // input from data file public static StringTokenizer tok; // parses lines from data file public static int count; public static void main(String args[]) throws IOException { in = new BufferedReader(new FileReader("polly.in")); ////////////////////////////////////////////////////////////////////// // MAIN INPUT/PROCESS/OUTPUT LOOP: ////////////////////////////////////////////////////////////////////// String line; count = 0; while ((line = in.readLine()) != null) { tok = new StringTokenizer(line); int degree = Integer.parseInt(tok.nextToken()); if (degree == 0) break; count++; int c[] = new int[degree + 1]; for (int i = 0; i <= degree; i++) { c[i] = Integer.parseInt(tok.nextToken()); // DEBUG: System.out.print(c[i] + " "); } // DEBUG: System.out.println(); int x = Integer.parseInt(tok.nextToken()); process(degree, c, x); } } public static void process(int degree, int c[], int x) { ////////////////////////////////////////////////////////////////////// // Implement Horner's rule. Count operations and coefficient digits. ////////////////////////////////////////////////////////////////////// int value = c[0]; int cost = -1; // initial "x" not multiplied for (int i = 1; i <= degree; i++) { value = value * x + c[i]; cost+=2; //once for "*", once for "x" if (c[i] != 0) cost+= 1 + (""+c[i]).length(); // "+" and coefficient length } cost++; // for the final "=" System.out.println("Polynomial " + count + ": " + value + " " + cost); } }