Computer >> Máy Tính >  >> Lập trình >> C ++

Bội số của 3 và 5 mà không sử dụng toán tử% trong C ++

Chúng ta có thể tìm bội số bằng cách sử dụng toán tử% mà không gặp bất kỳ trở ngại nào. Tuy nhiên, vấn đề nói rằng chúng tôi không thể sử dụng toán tử%.

Ở đây, chúng tôi sử dụng toán tử +. Chúng ta có thể lấy bội số bằng cách thêm 3 hoặc 5 vào bội số trước đó. Hãy xem một ví dụ.

Đầu vào

15

Đầu ra

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

Thuật toán

  • Khởi tạo số n.

  • Khởi tạo hai số để theo dõi bội số tiếp theo của 3 5.

  • Ban đầu hai số đó sẽ là 3 và 5.
  • Viết một vòng lặp lặp lại từ 1 sang n. Bao gồm cả hai.

    • Kiểm tra xem số hiện tại có phải là bội số của 3 hay không bằng cách sử dụng bản nhạc.

    • Tương tự, hãy kiểm tra bội số của 5.

    • Nếu chúng là bội số của 3 hoặc 5, hãy thêm số tương ứng với chúng để nhận bội số tiếp theo.

    • In văn bản tương ứng vào bảng điều khiển.

Thực hiện

Sau đây là cách thực hiện thuật toán trên trong 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;
}

Đầu ra

Nếu bạn chạy đoạn mã trên, thì bạn sẽ nhận được kết quả sau.

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