C++中不使用%運算子求3和5的倍數


我們可以很容易地使用%運算子找到倍數。但是,題目要求我們不能使用%運算子。

這裡,我們使用+運算子。我們可以透過對前一個倍數加3或5來得到倍數。讓我們看一個例子。

輸入

15

輸出

1
2
3 - Multiple of 3
4
5 - Multiple of 5
6 - Multiple of 3
7
8
9 - Multiple 3
10 - Multiple of 5
11
12 - Multiple of 3
13
14
15 - Multiple of both 3 and 5

演算法

  • 初始化數字**n**。

  • 初始化兩個數字來跟蹤**3**和**5**的下一個倍數。

  • 最初這兩個數字將是3和5。
  • 編寫一個迴圈,迭代從**1**到**n**。包含1和n。

    • 使用跟蹤變數檢查當前數字是否為3的倍數。

    • 同樣地檢查5的倍數。

    • 如果它們是3或5的倍數,則分別新增相應的數字以獲得下一個倍數。

    • 將相應的文字列印到控制檯。

實現

以下是上述演算法在C++中的實現

#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
Multiple of 3
52
53
Multiple of 3
Multiple of 5
56
Multiple of 3
58
59
Multiple of both 3 and 5
61
62
Multiple of 3
64
Multiple of 5
Multiple of 3
67
68
Multiple of 3
Multiple of 5
71
Multiple of 3
73
74
Multiple of both 3 and 5
76
77
Multiple of 3
79
Multiple of 5
Multiple of 3
82
83
Multiple of 3
Multiple of 5
86
Multiple of 3
88
89
Multiple of both 3 and 5
91
92
Multiple of 3
94
Multiple of 5
Multiple of 3
97
98
Multiple of 3
Multiple of 5

更新於:2021年10月27日

488 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.