Given an integer n, the task is to print all the numbers less than N that are divisible by both 3 and 5. A number divisible by both must be divisible by their LCM = 15. For Example:
Input: 50
Output: 0 15 30 45
Using for Loop with Step Size of 15
This method uses a for loop that jumps directly in steps of 15, since every number divisible by both 3 and 5 must be a multiple of 15. Thus, we avoid checking every number.
n = 100
for i in range(0, n, 15):
print(i, end=" ")
Output
0 15 30 45 60 75 90
Explanation:
- range(0, n, 15) produces numbers like 0, 15, 30, ...
- Each value is automatically divisible by 3 and 5.
Using Modulo Operator (% 15)
This method checks divisibility using a single modulo condition. If a number is divisible by 15, it is divisible by both 3 and 5.
n = 100
for i in range(n):
if i % 15 == 0:
print(i, end=" ")
Output
0 15 30 45 60 75 90
Explanation:
- for i in range(n): Loops from 0 to 99.
- i % 15 == 0 Checks if the remainder is zero when i is divided by 15.
Using Modulo Operator (% 3 and % 5 Separately)
This method checks divisibility by checking both conditions separately.
n = 100
for i in range(n):
if i % 3 == 0 and i % 5 == 0:
print(i, end=" ")
Output
0 15 30 45 60 75 90
Explanation:
- i % 3 == 0 checks divisibility by 3.
- i % 5 == 0 checks divisibility by 5.
- Both must be true to print the number.
Using List Comprehension
This method generates all required numbers in a single expression and prints them.
n = 100
nums = [i for i in range(n) if i % 15 == 0]
print(*nums)
Output
0 15 30 45 60 75 90
Explanation:
- List comprehension creates a list of all values where i % 15 == 0.
- print(*nums) prints the list items in a single line.