Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I have an assignment to find all the “magic numbers” within a range of numbers. A magic number is a number whose factors sums up to that number. My code below is not printing out the magic number. Can anyone help me with this.

public class MagicNumber {

/**

 * @param args

 */

public static void main(String[] args) {

    // TODO Auto-generated method stub

    System.out.print("What is the top of the range?");

    int range = IO.readInt();

    if (range <= 0 ) {

        IO.reportBadInput();

    }

    int sumOfFactors = 0;

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

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

            if (i % m == 0) {

                sumOfFactors = sumOfFactors + m;

            }

            if (sumOfFactors == i) {

                System.out.println(i);

                    }

            }

        }

    }

}

1 Answer

0 votes
by (13.1k points)

The problem is you are testing sumOfFactors == i while you are still summing factors. Move that outside the m loop. Then you need to set sumOfFactors to 0 before starting the m loop each time through the i loop, not just once at the start of the loop.

Want to learn java? Check out the java certification from Intellipaat.

Related questions

0 votes
1 answer
asked Feb 27, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Apr 1, 2021 in Java by Jake (7k points)
0 votes
0 answers
asked Feb 18, 2021 in Java by Harsh (1.5k points)
0 votes
1 answer
asked Feb 11, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Feb 8, 2021 in Java by dante07 (13.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...