I want to code a program to check if n is a multiple of 3 basing on the property that if the sum of its didigts is a multiple of 3, then so is n.
I try to reduce the number n until its smaller than 10 so that if it is equal to 3,6 or 9 n was originally a multiple of 3. Otherwise, it wasn't.
I am asked to use a recursive function called sum_of_digits to add up the digits of n as well as a recursive boolean function called is_multiple_of_3 to tell wether it is a multiple or not.
#include <iostream>
usingnamespace std;
int sum_digits(int n) {
if (n < 10) return n;
elsereturn sum_digits(n%10 + sum_digits(n/10));
}
bool is_multiple_3 (int n) {
int a = sum_digits(n);
if (a < 10) {
if (a == 3 or a == 6 or a == 9) returntrue;
elsereturnfalse;
}
elsereturn is_multiple_3(a);
}
int main () {
int n;
while (cin >> n) {
if (is_multiple_3(n)) cout << "SI" << endl;
else cout << "NO" << endl;
}
}
In my opinion this code should work perfectly, but somehow it doesen't. It appears that I am missing something or i am not considering a very special case.
unsignedint sum_digits(int n)
{
if (n < 0)
n = -n;
if (n < 10)
return n;
elsereturn sum_digits(n%10 + sum_digits(n/10));
}
bool is_multiple_3 (int n)
{
unsignedint a = sum_digits(n);
if (a < 10)
{
if (a == 3 or a == 6 or a == 9 or a==0)
returntrue;
elsereturnfalse;
}
elsereturn is_multiple_3(a);
}
#include <iostream>
staticconstexprint MAX = 1000000 ;
staticint sum[MAX] {0} ;
int sum_digits( int n ) // invariant: n > 0
{
if( n < MAX ) return sum[n] ;
elsereturn sum[n%MAX] + sum_digits( n/MAX ) ;
}
bool is_multiple_3( int n ) // invariant: n > 0
{
if( n < MAX ) return sum[n] == 0 ;
elsereturn is_multiple_3( sum_digits(n) ) ;
}
int main ()
{
std::cout.sync_with_stdio(false) ;
std::cin.tie(nullptr) ;
int v = 0 ;
for( int i = 0 ; i < MAX ; ++i )
{
sum[i] = v ;
++v ;
if( v == 3 ) v = 0 ;
}
int n ;
while( std::cin >> n )
std::cout << ( is_multiple_3(n) ? "SI" : "NO" ) << '\n' ;
}