在 C++ 中不使用 % 运算符的 3 和 5 的倍数

在本教程中,我们将编写一个程序,在不使用模 (%) 运算符的情况下打印 3 和 5 的所有倍数。

让我们看看解决问题的步骤。

  • 初始化数字n。

  • 初始化两个数字以跟踪下一个35 的倍数

  • 编写一个从1n迭代的循环两者都包括在内。

    • 检查35的倍数。

    • 如果其中任何一个匹配,则将倍数更新为下一个并打印结果。

示例

让我们看看代码。

#include <bits/stdc++.h>
using namespace std;
void findMultiplesOf3And5(int n) {
   int threeMultiple = 3;
   int fiveMultiple = 5;
   for (int i = 1; i <= n; i++) {
      bool _3 = false, _5 = false;
      if (i == threeMultiple) {
         threeMultiple += 3;
         _3 = true;
      }
      if (i == fiveMultiple) {
         fiveMultiple += 5;
         _5 = true;
      }
      if (_3 && _5) {
         cout << "Multiple of both 3 and 5" << endl;
      }else if (_3) {
         cout << "Multiple of 3" << endl;
      }else if (_5) {
         cout << "Multiple of 5" << endl;
      }else {
         cout << i << endl;
      }
   }
}
int main() {
   findMultiplesOf3And5(100);
   return 0;
}
输出结果

如果你运行上面的代码,那么你会得到下面的结果。

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
16
17
Multiple of 3
19
Multiple of 5
Multiple of 3
22
23
Multiple of 3
Multiple of 5
26
Multiple of 3
28
29
Multiple of both 3 and 5
31
32
Multiple of 3
34
Multiple of 5
Multiple of 3
37
38
Multiple of 3
Multiple of 5
41
Multiple of 3
43
44
Multiple of both 3 and 5
46
47
Multiple of 3
49
Multiple of 5

结论

如果您对本教程有任何疑问,请在评论部分提及。