15,665,942 members
1.00/5 (1 vote)
See more:
this is a model answer code (which I don't understand )

C++
```int threePlusTwo (int n)
{
if (n <= 2)
return 0;
if (n == 3)
return 2;
int twoSum = (n - 1) % 2 == 0? (n - 1): 0;
int threeSum = (n - 1) % 3 == 0? (n - 1): 0;
return twoSum + threeSum + threePlusTwo(n - 1);
}```

What I have tried:

C++
```#include<stdio.h>
#include<stdlib.h>
int tpt(int n)
{
if(n==1) return 0;
if(n%3==0||n%2==0) return n+tpt(n-1);

return tpt(n-1);
}```

the problem with my code is the test case that n>=6 it sums 6 only once because of the || condition...any ideas how to modify my code to pass that test case?!
Posted
Updated 7-Nov-17 2:53am
v2
CHill60 7-Nov-17 8:39am
What is it about the model answer that you don't understand - you've used all of the constructs in your own code except for the ternary/conditional operator ?: - How to use the Conditional (ternary) ope - C++ Forum[^]

## Solution 1

You must understand the meaning of the text of your homework and tranlate it into code:

"from range (1 to n-1)" translates to:
C++
```for( int i = 1; i < n; i++ ) {
//do magic stuff
}```

"sum all numbers divisable by 2" (some magic stuff)
C++
```if( (i %2) == 0) ) // % is modulo operator
{
sum = summ + n;
}```

Tip: use a else if statement for the 3 part.

Good luck with your homeworks. And write some tests for checking the correct results.

Richard MacCutchan 7-Nov-17 9:40am
I think that should be `sum = sum + i;`
Member 13476370 7-Nov-17 23:01pm
but how to modify my code to pass that test case

## Solution 2

Keep in mind you have to consider `(n-1)` as upper limit. Let's see how the model program could be intepreted

C
```if (n <= 2)
return 0;```
This is trivial, since `1` is not divisible by `2` or `3`.

C
```if (n == 3)
return 2;```
This is trivial too, since in the `1,2` sequence, there is only `2` which is divisible.

C
`int twoSum = (n - 1) % 2 == 0? (n - 1): 0;`
This means
C
```int twoSum;
if ( (n-1) % 2 == 0)
twoSum = (n-1);
else
twoSum = 0;```

That is "if (n-1) is divisible by `2` then keep it in order to add it to the sum".

The intepretation of
C
`int threeSum = (n - 1) % 3 == 0? (n - 1): 0;`
is similar.

C
`return twoSum + threeSum + threePlusTwo(n - 1);`
This makes the trick of adding two times a number which divisible both by `2` and `3` (please note such a requirement is not obvious from the question title).