How to check where a number is special number in C++

1 Answer

0 votes
// Special number = sum of the factorial of digits is equal to the number

#include <iostream>

int factorial(int num) {
	int fact = 1;

	while (num != 0) {
		fact = fact * num;
		num--;
	}

	return fact;
}

bool isSpecial(int num) {
	int sum = 0, tmp = num;

	while (tmp != 0) {
		sum += factorial(tmp % 10);
		tmp = tmp / 10;
	}

	return sum == num;
}

int main() 
{
	int num = 145; // 1! + 4! + 5! = 1 + 24 + 120 = 145

	if (isSpecial(num)) {
		std::cout << "yes" << std::endl;
	}
	else {
		std::cout << "no" << std::endl;
	}
}




/*
run:
 
yes
 
*/

 



answered Nov 25, 2023 by avibootz
edited Nov 25, 2023 by avibootz

Related questions

...