Alright. Ive been at this problem for a few days know and cant figure out what's wrong with my coding.

The Problem: Create a method called displayPerfectNumber in your own class named myMath. The method displayPerfectNumber asks a user to enter a integer number and displays every perfect number from 1 to the input integer number. A perfect number is one that equals the sum of all the numbers that divides evenly to into it. For example, 6 is perfect because 1,2 and 3 divide evenly into it, and their sum is 6; however, 12 is not a perfect number because 1,2,3,4, and 6 divide evenly into it, and their sum is greater than 13. Write a main method to call the method displayPerfectNumber.

Sample output

Input a integer number:
1000

The perfect number from 1 to 1000:
6
28
496

My Coding:

``````import java.util.Scanner;
public class MyMath
{
public void displayPerfectNumber()
{Scanner input = new Scanner (System.in);
int num = 1;
int N;
System.out.println("Enter a perfect number");
N = input.nextInt();
while(num <= N)
{
int i = 1;
int sum = 0;

while(i < num)
{
if(num % i == 0)
{
sum = sum+1;
i = i + 1;
}
if (sum == num)
{
System.out.println("num" + num);
num = num + 1;
}

}

}
}

}
``````

## All 2 Replies

You should probably actually write a helper method to do this. The helper method would figure out all of the numbers that divide perfectly into a given integer. It would return an ArrayList/array of these results. Then your other method add these numbers together to see if the Integer was a perfect number.

In order to figure out all of the numbers that divide perfectly into another number, you can use a for loop. Keep in mind that the % operator will tell return the "remainder" portion of a division. For example, 6 % 1 = 0, 6 % 2 = 0, 6 % 3 = 0. However, if you do 7 % 2 = 1 because 7/2 is 3 Remainder 1. Also, when writing your for loop, keep in mind that you only have to go half-way to the number - for example, if the number is 100, nothing above 50 can possibly divide evenly into 100, so it is a waste of time to check.

Hope that helps.

The method looks close to what you want but with some simple mistakes.

You test for the current number num being divisible in which case you count up another divisor in sum, (sum = sum+1), when in fact you want to add the test number i. You also increment i within the if statement but yiu will need to increment it whther it divides num or not!

As an aside, the inner while loop incrementing i might lend itself better to a for loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.