14S-Section-Solution

# 14S-Section-Solution - CS106A Handout 14S April 13th 15th...

This preview shows pages 1–2. Sign up to view the full content.

CS106A Handout 14S Spring 2011 April 13 th – 15 th , 2010 Section Solution Discussion Problem 1 Solution: Precedence The answer with Java’s precedence rules is –50. Discussion Problem 2 Solution: Perfect and Near Perfect Numbers Please remember that there is no single approach to solving these problems, and that provided you generate the expected results and the code is easy to understand, it’s all good. public class PerfectAndNearPerfectNumbers extends ConsoleProgram { public void run() { println("This program prints all of the perfect numbers between 1 and 10000"); println(); int numPerfect = 0; int numNearPerfect = 0; for (int n = 1; n <= 10000; n++) { int divisorSum = 0; for (int divisor = 1; divisor < n; divisor++) { if (n % divisor == 0) { divisorSum += divisor; } } if (divisorSum == n) { numPerfect++; println(" " + n + " is perfect."); } else if ((n - divisorSum <= 2) && (divisorSum - n <= 2)) { numNearPerfect++; println(" " + n + " is near perfect."); } } println(); println("There are these many perfect numbers between " +

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 3

14S-Section-Solution - CS106A Handout 14S April 13th 15th...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online