Sum of Multiples of 3 (Recursion)

I'm lost on this recursion stuff. It seems like a simple concept yet I cannot grasp it. So what I'm supposed to do is sum up the multiples of 3 in a given number using the sum3s function. This is what I have so far yet I don't even know what it is going to do really. I know what it is going to output but I just can't get it to get the sum of all the multiples of 3 in a number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
using namespace std;

int sum3s(int number)
{
  if(number <= 2)
      return 0;
  else if(number == 3)
      return 3; 
  else
      return (number + sum3s(number - 1));  
}

int main()
{
      int num;
  cout << "Enter number: ";
  cin >> num;
  
  cout << endl;
  
  cout << "The sum is " << sum3s(num);
}
Last edited on
You are not even using the modulos operator, so I have no idea how you are even attempting to solve this.


What do you know if the number is a multiple of 3?

You know that if 81 is a multiple of 3, then 78, 75, 72, 69, 66, ..., 3 are all multiples of the number 3. What pattern is common in all those numbers?

The sum of all numbers 3 to N which are multiples of the number 3 is:

= 1 * 3 + 2 * 3 + 3 * 3 + 4 * 3 + ... + N
= 3 (1 + 2 + 3 + 4 + ... + N / 3)

We can now apply gauss's sum of series method to this to obtain the formula:
= (3 / 2) * (N / 3 * (N / 3 + 1))
sum of series http://mathcentral.uregina.ca/QQ/database/QQ.02.06/jo1.html

If you sub in 81 for N, you get 1134

You can now choose to re-curse until you find a number which is a multiple of 3, then apply the above formula
Last edited on
Topic archived. No new replies allowed.