Home > Mobile >  Algorithm to get the submultiples of each number in a range
Algorithm to get the submultiples of each number in a range

Time:07-21

I have this exercise in mind, I keep trying to solve it in Java but I'm not able to create a correct algorithm to get the submultiples of each number in a range, the start and the end of the range is user defined. Besides, the number 1 doesn't count as a submultiple.

For example, in a range between 3 and 9, the output of the app would be:

start: 3
end: 9

Submultiples of 3:  Doesn't have submultiples
Submultiples of 4:  2
Submultiples of 5:  Doesn't have submultiples
Submultiples of 6:  3 2  
Submultiples of 7:  Doesn't have submultiples
Submultiples of 8:  4 2
Submultiples of 9:  3

It would be very helpful if someone can help me with this exercise. Thanks for reading!

CodePudding user response:

You can do it using to nested loops, like this:

class HelloWorld {
    public static void main(String[] args) {
        int start = 3;
        int end = 9;
        boolean foundMultiples = false;
        for(int i=start; i<=end; i  ) {
            foundMultiples = false;
            System.out.print("Submultiples of "   i   ": ");
            for(int j = 2; j < i; j  ) {
                if(i % j == 0) {
                    foundMultiples = true;
                    System.out.print(j   " ");
                }
            }
            if(!foundMultiples) {
                System.out.print("Doesn't have submultiples");
            }
            System.out.println();
        }
    }
}

Here, we loop through the user entered range, and then found multiples of each number in an inner loop. We keep track of if any multiple was found, using a boolean variable.

  • Related