CSE142 Programming Examples handout #16 // post: returns true if and only if s satisfies the rule: "i before e // except after c" public static boolean ieOkay(String s) { s = s.toLowerCase(); for (int i = 0; i < s.length() - 1; i++) { if (s.substring(i, i + 2).equals("ei")) { if (i == 0 || s.charAt(i - 1) != 'c') return false; } } return true; } // pre : n >= 2 // post: prints the prime factorization of n public static void showFactors(int n) { System.out.print(n + " = "); int i = 2; boolean first = true; while (i <= n) { if (n % i == 0) { if (first) { first = false; } else { System.out.print(" * "); } System.out.print(i); n /= i; } else { i++; } } System.out.println(); } // pre : n >= 2 // post: prints the prime factorization of n. This version is much more // efficient than the first because it stops when it has examined a // number larger than the square root of the largest prime in n. public static void showFactors2(int n) { System.out.print(n + " = "); int i = 2; while (i * i <= n) { if (n % i == 0) { System.out.print(i + " * "); n /= i; } else { i++; } } System.out.println(n); }
Stuart Reges
Last modified: Mon Oct 31 19:09:12 PST 2005