How to find all multiples of 3 and 5 up to number N

A number, xx, is said to be a multiple of another number, yy, if the remainder of x/yx/y is 00. Similarly, a number, nn, will be a multiple of 3 and 5 if the remainder of n/3n/3 and n/5n/5 is equal to 00.

In order to find all the numbers from 00 to NN that are multiples of 3 and 5, each number needs to be considered separately, and the remainders of both n/3n/3 and n/5n/5 should be compared to 00.

Since the range 00 to NN is traversed only once, the time complexity of this algorithm is O(n)O(n).

Implementation

The following code implements this algorithm in C++, Java, and Python:

#include <iostream>
using namespace std;
void findMultiples(int n){
for(int i = 0; i <= n; i++)
if(i % 3 == 0 && i % 5 == 0)
cout << i << endl;
}
int main() {
findMultiples(120);
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved