C++ Program to find factorial within given range and then add the digits of result to form single digit answer

Problem : Problem is to find the factorial of a number e.g. 4
4 ! = 24
Then add the digits of the result to form a single digit result i.e
4! = 24 & 2+4 = 6
6 is the result here.

Secondly and the most important thing is to provide the solution in most effective way.

Try your self first then try this one:
#include <iostream>
#include <conio.h>
using namespace std;

long long factorial(long long number) {
if (number <= 2) return 2;

return factorial(number - 1) * number;
}

void main()
{
// any Range
int min = 4;
int max = 20;

long long fact = factorial(min);
int multipleByNine = fact % 9;

cout <min < ": " < fact <": " < (multipleByNine == 0 ? 9 : multipleByNine)<endl;

for (int index = min + 1; index <= max; ++index)
{
fact *= index;
multipleByNine = fact % 9;

cout < index < ": " < fact < ": " < (multipleByNine == 0 ? 9 : multipleByNine) < endl;
}

_getch();
}

Comments

Popular Posts