In các số từ 1 đến N, đánh dấu bội của 3, 5, hoặc cả hai — không dùng toán tử %.
Ý tưởng: giữ biến next3 = 3, next5 = 5. Khi i == next3 thì in "Multiple of 3", next3 += 3. Tương tự cho 5.
Triển khai C++
#include <bits/stdc++.h>
using namespace std;
void findMultiplesOf3And5(int n) {
int next3 = 3, next5 = 5;
for (int i = 1; i <= n; i++) {
bool is3 = false, is5 = false;
if (i == next3) { next3 += 3; is3 = true; }
if (i == next5) { next5 += 5; is5 = true; }
if (is3 && is5) cout << "Multiple of both 3 and 5";
else if (is3) cout << "Multiple of 3";
else if (is5) cout << "Multiple of 5";
else cout << i;
cout << endl;
}
}
int main() {
findMultiplesOf3And5(15);
return 0;
}
Kết quả (N=15)
1 2 Multiple of 3 4 Multiple of 5 Multiple of 3 7 8 Multiple of 3 Multiple of 5 11 Multiple of 3 13 14 Multiple of both 3 and 5