Print first m multiples of n without using any loop in Python
Last Updated :
13 Apr, 2023
Given n and m, print first m multiples of a m number without using any loops in Python. Examples:
Input : n = 2, m = 3
Output : 2 4 6
Input : n = 3, m = 4
Output : 3 6 9 12
We can use range() function in Python to store the multiples in a range. First we store the numbers till m multiples using range() function in an array, and then print the array with using (*a) which print the array without using loop. Below is the Python implementation of the above approach:
Python3
def multiple(m, n):
a = range (n, (m * n) + 1 , n)
print ( * a)
m = 4
n = 3
multiple(m, n)
|
Output:
3 6 9 12
Note : In Python 3, print(*(range(x)) is equivalent to print(” “.join([str(i) for i in range(x)]))
Approach: Using numpy arange() with reshape()
note: install numpy module using command “pip install numpy”
Here’s a method to solve this problem using the NumPy library’s arange() function and the reshape() function:
Algorithm:
Create a numpy array using arange() function with start as n and stop as (m*n)+n, and step as n.
Reshape the numpy array using reshape() function to a (m,1) matrix.
Convert the numpy array to a list using tolist() function.
Print the list using * operator.
Python3
import numpy as np
def multiple(m, n):
a = np.arange(n, m * n + 1 , n)
a = a.reshape( 1 , - 1 )
result = ' ' .join(a[ 0 ].astype( str ))
print (result)
m = 4
n = 3
multiple(m, n)
|
Output:
3 6 9 12
Time Complexity: The time complexity of this algorithm is O(m) as we are creating a numpy array with m elements and then reshaping it, which takes constant time.
Auxiliary Space: The space complexity of this algorithm is O(m) as we are creating a numpy array with m elements and then reshaping it, which takes constant space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...