Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Logic error

  Asked By: Ernesta    Date: Apr 14    Category: Java    Views: 836
  

Logic Problem, I'm new to java but have experience with many other
languages. I've been working on an exercise, but one or two answers that my
program is generating have me puzzled. The program is to list the perfect
numbers between 1 and 1000. Perfect numbers are numbers whos
factors(excluding itself) can be added to equal the original number. I keep
getting an output of 6, 24, 28, and 496. The 24 has me stumped. Where is
my logic error? The program is below:

public class Perfect
{
public static void main(String[] args)
{
int count;
int total;
int num;
System.out.print("Perfect numbers between 1 and 1000 are: ");
for (count = 1; count < 1000; ++count)
{
total = 0;
for (num = 1; num < count; ++num)
{
if(count%num == 0)
{
total = total + num;
}
if(total == count)
{
System.out.print(count + " ");
num = count;
}
}
}
}
}

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Phoebe Brown     Answered On: Apr 14

public class PerfectNumberGenerator{

private static int max = 1000;

public static void main(String[] args){
for (int i = 1;i <= max; i++){
if (isPerfect(i)){
System.out.println(String.valueOf(i) + " is perfect.");
}
}
}

public static boolean isPerfect(int n){
int sum = 0;
for (int i = 1; i < n; i++){
if (n%i == 0) sum = sum + i;
}
return (sum == n);
}
}

 
Answer #2    Answered By: Latoya Murray     Answered On: Apr 14

The test
if(total == count)
must be done outside the loop
for (num = 1; num < count; ++num)
24 gets printed because 24 = 1+2+3+4+6+8. In your code, you don't get to verify
12.

Also, for efficiency, you may want to consider replacing this loop with:
for (num = 1; num <= count/2; ++num)

 
Didn't find what you were looking for? Find more on Logic error Or get search suggestion and latest updates.




Tagged: