Print Numbers Divisible by 3 or 5
Print all numbers from 1 to n that are divisible by 3 or 5.
Sample input
15
Sample output
3 5 6 9 10 12 15
Solution
n = 15
result = [i for i in range(1, n + 1) if i % 3 == 0 or i % 5 == 0]
print(*result)
const n = 15;
const result = [];
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 || i % 5 === 0) result.push(i);
}
console.log(result.join(" "));
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int n = 15;
System.out.println(IntStream.rangeClosed(1, n).filter(i -> i % 3 == 0 || i % 5 == 0)
.mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
fun main() {
val n = 15
val result = (1..n).filter { it % 3 == 0 || it % 5 == 0 }
println(result.joinToString(" "))
}
let n = 15
let result = (1...n).filter { $0 % 3 == 0 || $0 % 5 == 0 }
print(result.map(String.init).joined(separator: " "))
void main() {
int n = 15;
final result = <int>[];
for (var i = 1; i <= n; i++) {
if (i % 3 == 0 || i % 5 == 0) result.add(i);
}
print(result.join(' '));
}
#include <iostream>
using namespace std;
int main() {
int n = 15;
bool first = true;
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 || i % 5 == 0) {
if (!first) cout << " ";
cout << i;
first = false;
}
}
cout << endl;
return 0;
}
#include <stdio.h>
int main() {
int n = 15, first = 1;
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 || i % 5 == 0) {
if (!first) printf(" ");
printf("%d", i);
first = 0;
}
}
printf("\n");
return 0;
}