c++algorithmsumproduct

Fastest way to sum 3 numbers digits


I'm trying to solve this problem:

You get 3 different numbers as input, of different length, you have to determine the sum of the digits of all 3 numbers and also the product.

...like this:

#include <bits/stdc++.h>

using namespace std;

int main () {
    int a, b, c, S, P;
    cin >> a >> b >> c;
    S = 0;
    P = 1;
    
    while (a != 0) {
        int c1 = a % 10;
        S += c1;
        P *= c1;
        a /= 10;
    }
    while (b != 0) {
        int c1 = b % 10;
        S += c1;
        P *= c1;
        b /= 10;
    }
    while (c != 0) {
        int c1 = c % 10;
        S += c1;
        P *= c1;
        c /= 10;
    }
    cout << S << ' ' << P << endl;
}

Is there a way to solve this more efficient?


Solution

  • You should bother not about the fastest way that does not make sense for such a simple program but about the correctness of the code and avoiding its duplication.

    Your program is just incorrect.

    For starters the user can interrupt the input. In this case at least one of the variables a, b, c will have indeterminate value. As a result the program will have undefined behavior.

    Secondly, as you are using the signed int type when the user can enter negative numbers. In this case you will get an incorrect result because for example sum of digits can occur to be negative.

    Thirdly, the user can enter 0 as a value of a number. In this case this number will be skipped in a while loop like this

    while (a != 0) {
    

    In this case you again will get an incorrect result because the product of digits can be not equal to zero though it must be equal to zero in this case.

    The same while loops are duplicated. That is the program has a redundant code.

    The program can be written the following way as it is shown in the demonstrative program below.

    #include <iostream>
    
    int main() 
    {
        long long int a = 0, b = 0, c = 0;
    
        std::cin >> a >>b >> c;
    
        long long int sum = 0;
        long long int product = 1;
    
        for ( int num : { a, b, c } )
        {
            const long long int Base = 10;
            do
            {
                long long int digit = num % Base;
    
                if ( digit < 0 ) digit = -digit;
    
                sum += digit;
                if ( product ) product *= digit;
            } while ( num /= Base );
        }
    
        std::cout << "sum = " << sum << '\n';
        std::cout << "product = " << product << '\n';
    
        return 0;
    }