In this tutorial, we are going to write a program to find out m multiples of a number n without using loops. For example, we have a number n = 4 and m = 3, the output should be 4, 8, 12. Three multiples of four. Here, the main constraint is not to use loops.
We can use the range() function to get the desired output without loops. What is the work of the range() function? range() function returns a range object which we can convert into an iterator.
Let's see the syntax of range().
Syntax
range(start, end, step)
Algorithm
start - starting number to the range of numbers end - ending number to the range of numbers (end number is not included in the range) step - the difference between two adjacent numbers in the range (it's optional if we don't mention then, it takes it as 1) range(1, 10, 2) --> 1, 3, 5, 7, 9 range(1, 10) --> 1, 2, 3, 4, 5, 6, 7, 8, 9
Example
## working with range() ## start = 2, end = 10, step = 2 -> 2, 4, 6, 8 evens = range(2, 10, 2) ## converting the range object to list print(list(evens)) ## start = 1, end = 10, no_step -> 1, 2, 3, 4, 5, 6, 7, 8, 9 nums = range(1, 10) ## converting the range object to list print(list(nums))
Output
If you run the above program, you will get the following results.
[2, 4, 6, 8] [1, 2, 3, 4, 5, 6, 7, 8, 9]
Now, we will write our code to the program. Let's see the steps first.
Algorithm
Now, we will write our code to the program. Let's see the steps first.
1. Initialize n and m. 2. Write a range() function such that it returns multiples of n. 3. Just modify the step from the above program to n and ending number to (n * m) + 1 starting with n.
See the code below.
Example
## initializing n and m n = 4 m = 5 ## writing range() function which returns multiples of n multiples = range(n, (n * m) + 1, n) ## converting the range object to list print(list(multiples))
Output
If you run the above program, you will get the following results.
[4, 8, 12, 16, 20]
Conclusion
I hope you enjoyed the tutorial, if you have any doubts regarding the tutorial, mention them in the comment section.