Sunday, July 10, 2011

Program to Print Perfect Numbers

Problem: Greek mathematicians took special interest in numbers that are equal to the sum of their proper divisors (a proper divisor of n is any divisor less than n itself). They called such numbers *perfect numbers*. For example, 6 is a perfect number because it is the sum of 1, 2 and 3, which are numbers less than 6 that divide equally into 6. Similarly, 28 is a perfect number because it is the sum of 1, 2, 4, 7, and 14.


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.

3 comments:

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

    ReplyDelete
  2. Here is my version:

    import 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;
    }

    }

    ReplyDelete