Code
class DivisibleThreeFive
{
// Result function with N
static void result(int N)
{
// iterate from 0 to N
for (int num = 0; num < N; num++)
{
if (num % 3 == 0 && num % 5 == 0)
System.out.print(num + " ");
}
}
public static void main(String []args)
{
int N = 100;
result(N);
}
}
Output
0 15 30 45 60 75 90
Time Complexity: O(N)
Auxiliary Space: O(1)
Method - 2
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.
class DivisibleThreeFive
{
public static void main(String[] args)
{
int n = 100;
for (int i = 0; i < n; i += 15)
{
System.out.print(i + " ");
}
}
}
- Time Complexity: O(n/15) ~= O(n)
- Auxiliary Space: O(1)