Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print first m multiples of n without using any loop in Python
In this tutorial, we will write a program to find the first m multiples of a number n without using loops. For example, if n = 4 and m = 3, the output should be 4, 8, 12 (three multiples of four). The main constraint is avoiding loops.
We can use the range() function to achieve this without loops. The range() function returns a range object that generates a sequence of numbers.
Syntax
range(start, stop, step)
Parameters
- start − Starting number of the range
- stop − Ending number (not included in the range)
- step − Difference between adjacent numbers (optional, default is 1)
Example: Understanding range()
Let's see how range() works with different parameters ?
# range() with step parameter
evens = range(2, 10, 2)
print("Even numbers:", list(evens))
# range() without step (default step = 1)
nums = range(1, 10)
print("Numbers 1-9:", list(nums))
# range() for multiples of 3
threes = range(3, 16, 3)
print("Multiples of 3:", list(threes))
Even numbers: [2, 4, 6, 8] Numbers 1-9: [1, 2, 3, 4, 5, 6, 7, 8, 9] Multiples of 3: [3, 6, 9, 12, 15]
Finding First m Multiples of n
To find the first m multiples of n, we need ?
-
start =
n(first multiple is n itself) -
stop =
(n * m) + 1(to include the mth multiple) -
step =
n(increment by n each time)
Example
# Find first 5 multiples of 4
n = 4
m = 5
multiples = range(n, (n * m) + 1, n)
print(f"First {m} multiples of {n}:", list(multiples))
First 5 multiples of 4: [4, 8, 12, 16, 20]
Example with Different Values
# Find first 6 multiples of 7
n = 7
m = 6
multiples = range(n, (n * m) + 1, n)
print(f"First {m} multiples of {n}:", list(multiples))
# Find first 4 multiples of 9
n = 9
m = 4
multiples = range(n, (n * m) + 1, n)
print(f"First {m} multiples of {n}:", list(multiples))
First 6 multiples of 7: [7, 14, 21, 28, 35, 42] First 4 multiples of 9: [9, 18, 27, 36]
How It Works
The formula range(n, (n * m) + 1, n) works because ?
- Starting at
ngives us the first multiple - Stepping by
ngives us successive multiples - Stopping at
(n * m) + 1ensures we get exactlymmultiples
Conclusion
Using range(n, (n * m) + 1, n) efficiently generates the first m multiples of n without loops. This approach leverages Python's built-in range function to create a clean, readable solution.
