Multiples of 3 and 5 without using % operator in C++

We can find the multiples using % operator without any hurdles. But, the problem states that we can't use % operator.

Here, we make use of the + operator. We can get the multiples by adding 3 or 5 to the previous multiple. Let's see an example.

Input

15

Output

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

Algorithm

  • Initialise the number n.

  • Initialise two number to keep track of next multiple of 3 and 5.

  • Initially those two numbers will be 3 and 5.
  • Write a loop that iterates from 1 to n. Both inclusive.

    • Check whether the current number is multiple of 3 or not using the track variably.

    • Similarly check for the multiple of 5.

    • If they are multiple of 3 or 5, add respective number to them to get the next multiple.

    • Print the corresponding text to the console.

Implementation

Following is the implementation of the above algorithm in C++

#include 
using namespace std;
void findMultiplesOf3And5(int n) {
   int threeMultiple = 3;
   int fiveMultiple = 5;
   for (int i = 1; i 

Output

If you run the above code, then you will get the following result.

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
Updated on: 2021-10-27T06:28:22+05:30

735 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements