16a-class-examples

16a-class-examples - for (int i = 1; i <= bound;...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
Handout #16A CS 106A July 6, 2009 Solution to the “Perfect Number” Problem Program to determine list perfect numbers /* * File: FindPerfect.java * ---------------------- * This program finds perfect numbers. */ import acm.program.*; /* * This class finds all perfect numbers up to a user-specified * upper bound. */ public class FindPerfect extends ConsoleProgram { public void run() { int bound = readInt("Enter upper bound: ");
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: for (int i = 1; i <= bound; i++) { if (isPerfect(i)) println(i); } } /* Returns true if its argument is a perfect number */ private boolean isPerfect(int n) { return sumOfProperDivisors(n) == n; } /* Returns the sum of the proper divisors of n */ private int sumOfProperDivisors(int n) { int sum = 0; for (int i = 1; i < n; i++) { if (n % i == 0) sum += i; } return sum; } }...
View Full Document

Ask a homework question - tutors are online