Perfect numbers 1 to n

user605989 picture user605989 · Feb 21, 2011 · Viewed 9.8k times · Source

Write an algorithm that prints perfect numbers from 1 to n. To determine if a number is perfect add up all the factors of the number that are less than the number. If the sum is equal to the number, it is perfect.

import java.util.Scanner;

public class Assign_6 {

    public static void main(String[] args){

        int num,number,sum=0,factor;

        System.out.print("Enter Number");
        Scanner keyboard = new Scanner (System.in);

        number=keyboard.nextInt();

        for (num=1;num<number;num++){
            for(factor=1;factor<number;factor++){
                if(num%factor==0){
                    sum= sum+factor;
                }
                if(sum==num){
                    System.out.println(sum);
                }
                sum=0;
            }

        }
    }
}

Output: 24

Nothing prints out. Don't know whats wrong. Where am I going wrong? I can only use while, for, and else-if statements.

Answer

biziclop picture biziclop · Feb 21, 2011

Print out the sum for every number (and not just when sum==number) and you'll be able to figure it out.

(Two clues: correct indentation helps find matching { } pairs quickly. And it pays to give your variables descriptive names.)