Search code examples
c++stringintegerfactorialfunction-definition

Display a factorial sequence as a string


// here is my code to find a factorial of a number:

int get_factorial(int num)
{
   auto sum = 1;
   while(num > 0)
   {
       sum = sum * num;
       num--;
   }

   return sum;
}

// this works to give me the factorial but my assignment wants me to return a string. so if my parameter is 5, instead of returning 120 like my code does currently I need it to return a string that says "1x2x3x4x5 = 120". "5x4x3x2x1 = 120" should also work.

I'm unsure where to start. I thought maybe creating a string and appending each sum as it goes through the loop but I don't know how to do that.


Solution

  • The assignment is not easy for beginners like you and me.:)

    I can suggest the following solution shown in the demonstration program below.

    #include <iostream>
    #include <string>
    
    std::string get_factorial( unsigned int n )
    {
        std::string result;
        unsigned long long factorial = 1;
    
        while (n > 1)
        {
            result += std::to_string( n ) + 'x';
            factorial *= n--;
        }
    
        return result + std::to_string( n ) + " = " + std::to_string( factorial );
    }
    
    int main()
    {
        for (unsigned int i = 0; i < 10; i++)
        {
            std::cout << get_factorial( i ) << '\n';
        }
    }
    

    The program output is

    0 = 1
    1 = 1
    2x1 = 2
    3x2x1 = 6
    4x3x2x1 = 24
    5x4x3x2x1 = 120
    6x5x4x3x2x1 = 720
    7x6x5x4x3x2x1 = 5040
    8x7x6x5x4x3x2x1 = 40320
    9x8x7x6x5x4x3x2x1 = 362880
    

    Alternatively the function can look also the following way as in that demonstration program.

    #include <iostream>
    #include <string>
    
    std::string get_factorial( unsigned int n )
    {
        std::string result = std::to_string( n == 0 ? 0 : 1 );
        unsigned long long factorial = 1;
    
        for ( unsigned int i = 1; i++ < n; )
        {
            result += 'x' + std::to_string(i);
            factorial *= i;
        }
    
        return result  + " = " + std::to_string( factorial );
    }
    
    int main()
    {
        for (unsigned int i = 0; i < 10; i++)
        {
            std::cout << get_factorial( i ) << '\n';
        }
    }
    

    The program output is

    0 = 1
    1 = 1
    1x2 = 2
    1x2x3 = 6
    1x2x3x4 = 24
    1x2x3x4x5 = 120
    1x2x3x4x5x6 = 720
    1x2x3x4x5x6x7 = 5040
    1x2x3x4x5x6x7x8 = 40320
    1x2x3x4x5x6x7x8x9 = 362880
    

    Pay attention to that the type unsigned long long int can store the maximum value of factorial for n equal to 20.