Writing a program that loops factors from 1-100. It is supposed to stop when it reaches a number that has nine factors

386 views Asked by At

I have count incrementing but it doesn't seem to be working. It just keeps running to one hundred. Does anyone have any ideas?

public class Main<x> {

    public static void main(String[] args) {
        int count = 0;
        for(int i = 1; i <= 100; i++) {
            System.out.print("Factors of " + i + ": ");
            for(int j = 1; j < i; j++)
                if(i % j == 0) {
                    count++;
                    if (count == 9)
                        break;
                    System.out.print(j + " ");

                }

            System.out.println("");
 }
}
1

There are 1 answers

0
Mr.AK On

There are a couple of things I would like to share, First the Maths, A number is always a considered a factor of itself, so one of the changes will be the check j<i updated to j<=i inside you nested for, but if you have made it intentionally then you need not update it.

Other than this, the math seems to be alright, another thing to look at is how your if block is working, your check for count should come outside the check for factor i.e. if(i % j == 0) and for that matter even outside the second for loop, since the break will take you outside the for loop it is being hit, since you need to stop the iteration completely i.e. the next number should not be hit, once you get first number with 9 factors you need to keep your break in the first for loop.

Your final code should look something like this:

public class Main
{
    public static void main(String[] args) {
        for(int i = 1; i <= 100; i++) {
            int count = 0;
            System.out.print("Factors of " + i + ": ");
            for(int j = 1; j <= i; j++) {
                if(i % j == 0) {
                    System.out.print(j + " ");
                    count++;
                }
            }

            System.out.println("\n");
            if (count >= 9) {
                break;
            }
        }
    }
}

Hope it helps!!