Write a predicate method isPerfect(n) that returns *true* if the integer n is perfect, and *false* otherwise. Test your implementation by writing a main program that uses the isPerfect method to check for perfect numbers in the range 1 to 9999 by testing each number in turn. Whenever it identifies a perfect number, your program should display that number on your screen. Your program should find two other perfect numbers in that range as well. (Roberts ch 5, problem 12).

What it looks like:

/* * File: printPerfects.java * Name: Chu * Section Leader: * This program prints the numbers between 1 and 9999 that are perfect numbers. Perfect numbers are those * where the divisors (integers that divide evenly into it) all sum up to that number. It uses the private * predicate method isPerfect. * */ package ch6_practice; import acm.program.*; public class printPerfects extends ConsoleProgram { public void run() { for (int i = 1; i < 9999; i++) { if (isPerfect(i)) { println(i); } } } private boolean isPerfect (int n) { int sum = 0; for (int i = 1; i < n; i++) { if (n % i == 0) { sum += i; } } if (sum == n) { return true; } else return false; } }

This was a simple little program that simply re-enforced the practice of breaking certain operations of a program into their own methods. The method "isPerfect" creates a new variable "sum", initialized at a value of zero. For any number that you're testing to see if it is perfect, you find all the divisors via brute force. Whenever you find a divisor, you add it to "sum." If, after finding all the divisors, the value of "sum" equals the number you're testing, then you know that the number is perfect.

this is great

ReplyDeleteis there a cprogram in this problem?i really need it.

ReplyDeleteSant Ritz is more than just a home. Its combination

ReplyDeleteof condominium status with contemporary ville living.

the interlace condo

Here is my version:

ReplyDeleteimport acm.program.*;

public class testPerfect extends ConsoleProgram{

public void run(){

for (int i = 1; i < 10000; i++){

if (isPerfect(i)) println(i);

}

}

private boolean isPerfect(int n){

if (n % 2 != 0) return false;

int sum = 0;

for (int i = (n/2); i > 0; i--){

if (n % i == 0){

sum += i;

}

}

if (sum == n){

return true;

}else return false;

}

}