// 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>
#include <iterator>
std::string get_factorial( unsigned int n )
{
std::string result;
unsigned long long factorial = 1;
while (n > 1)
{
factorial *= n;
result += std::to_string( n ) + 'x';
--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