Start learning free

LESSON 124 OF 348 · WHILE LOOPS & FOR LOOPS

Print Multiples in Scala

Practice

Given two positive integers A and B, print to the console the first A non-negative numbers that are divisible by B

A number X is divisible by B if X modulo B == 0

Example:

Input: A = 5, B = 3

Output:
3
6
9
12
15

Explanation:
The first 5 positive integers that are divisible by 3 are
3, 6, 9, 12 and 15
1 modulo 3 = 1 => not divisible
2 modulo 3 = 2 => not divisible
3 modulo 3 = 0 => divisible
4 modulo 3 = 0 => not divisible
5 modulo 3 = 0 => not divisible
6 modulo 3 = 0 => divisible
7 modulo 3 = 0 => not divisible
8 modulo 3 = 0 => not divisible
9 modulo 3 = 0 => divisible
10 modulo 3 = 0 => not divisible
11 modulo 3 = 0 => not divisible
12 modulo 3 = 0 => divisible
13 modulo 3 = 0 => not divisible
14 modulo 3 = 0 => not divisible
15 modulo 3 = 0 => divisible
Hints:

If we look at the explanation, a simple algorithm comes to mind:
Start by iterating from 1 and check if it is divisible by B.
Keep a counter of how many numbers you printed so far.
Stop when you reached the A number of printed numbers.
STEP 1 OF 7
    Ctrl + Enter to check

    Print Multiples in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free