Python Program to print all the numbers divisible by 3 and 5 for a given number
Last Updated :
01 Feb, 2023
Given the integer N, the task is to print all the numbers less than N, which are divisible by 3 and 5.
Examples :
Input : 50
Output : 0 15 30 45
Input : 100
Output : 0 15 30 45 60 75 90
Approach: For example, let’s take N = 20 as a limit, then the program should print all numbers less than 20 which are divisible by both 3 and 5. For this divide each number from 0 to N by both 3 and 5 and check their remainder. If remainder is 0 in both cases then simply print that number.
Below is the implementation :
Python3
def result(N):
for num in range (N):
if num % 3 = = 0 and num % 5 = = 0 :
print ( str (num) + " " , end = "")
else :
pass
if __name__ = = "__main__" :
N = 100
result(N)
|
Output
0 15 30 45 60 75 90
Time Complexity: O(N)
Auxiliary Space: O(1)
Alternative Method: This can also be done by checking if the number is divisible by 15, since the LCM of 3 and 5 is 15 and any number divisible by 15 is divisible by 3 and 5 and vice versa also.
Python3
n = 50
for i in range ( 0 ,n):
if i % 15 = = 0 :
print (i,end = " " )
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Alternate Method:Using list comprehension.
Python3
n = 50
result = [i for i in range (n) if i % 3 = = 0 and i % 5 = = 0 ]
print (result)
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Please refer complete article on Program to print all the numbers divisible by 3 and 5 for a given number for more details!
Share your thoughts in the comments
Please Login to comment...