JavaScript Program to Print All Numbers Divisible by 3 and 5 of a Given Number
Last Updated :
04 Sep, 2023
In this article, we are going to discuss how to print all the numbers that are divisible by 3 and 5. We will write a program for finding out those numbers. For this, we can use loop or conditional statements.
Example:
Input: 75
Output: 0, 15, 30, 45, 60, 75
Input: 150
Output: 0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150
We can solve this by using the following methods:
- Using for loop
- Using LCM method
- Using the arithmetic series formula
Approach 1: Using for Loop
Using n = 50 as an example, the program should output all numbers below 50 that are divisible by both 3 and 5. To do this, divide each number between 0 and n by 3 and 5 in a for loop. Print that value if the remainder in both scenarios is 0.
Example: This example describes how can we print numbers that are divisible by 3 and 5 using a for loop.
Javascript
function divisibleBy3and5(n) {
for (let i = 0; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
console.log(i)
}
}
}
let N = 50;
divisibleBy3and5(N);
|
Time Complexity: It is taking O(N) time as for loop will iterate n (given number) times.
Auxiliary Space: The space complexity of the above code is O(1), as no extra space is required in order to complete the operation.
Approach 2: Using LCM Method
Here we are taking LCM of 3 anad 5 which is 15. If any number which is divisible by 15 it means it can also divisible by 3 and 5 so we are only searching for that number which is divisible by 15 and printing that number only.
Example: This example is showing how can you print number which are divisible by 3 and 5 using LCM
Javascript
let n = 50;
for (let i = 0; i <= 50; i++) {
if (i % 15 == 0) {
console.log(i);
}
}
|
Time Complexity: The time complexity will be O(n) as loop will iterate n times.
Auxiliary Space: The space complexity of the above code is O(1), as no extra space is required in order to complete the operation.
Approach 3: Using the Arithmetic Series Formula
In this approach, we are going to iterate everytime with the increment of 15, as 15 is the LCM of 3 and 5, And if number is divisible by 15 then it will also be divisible by 3 and 5. And it will only work if we are starting our iteration from 0.
Example: This example describes how you can find out the numbers which are divisible by 3 and 5 using arithmetic series formula
Javascript
let n = 150;
function divisibility(n) {
for (let i = 0; i <= n; i += 15) {
console.log(i);
}
}
divisibility(n);
|
Output
0
15
30
45
60
75
90
105
120
135
150
Time Complexity: The time complexity will be O(n) as loop will iterate n times.
Auxiliary Space: The space complexity of the above code is O(1), as no extra space is required in order to complete the operation.
Share your thoughts in the comments
Please Login to comment...