Strong Number
A strong number equals the sum of the factorials of its digits (e.g. 145 = 1! + 4! + 5!).
Sample input
145
Sample output
true
Solution
import math
n = 145
total = sum(math.factorial(int(d)) for d in str(n))
print(total == n)
function factorial(x) {
let f = 1;
for (let i = 2; i <= x; i++) f *= i;
return f;
}
const n = 145;
let total = 0;
for (const d of String(n)) total += factorial(Number(d));
console.log(total === n);
public class Main {
static int factorial(int x) {
int f = 1;
for (int i = 2; i <= x; i++) f *= i;
return f;
}
public static void main(String[] args) {
int n = 145, total = 0;
for (char c : String.valueOf(n).toCharArray()) {
total += factorial(c - '0');
}
System.out.println(total == n);
}
}
fun factorial(x: Int): Int {
var f = 1
for (i in 2..x) f *= i
return f
}
fun main() {
val n = 145
var total = 0
for (c in n.toString()) {
total += factorial(c - '0')
}
println(total == n)
}
func factorial(_ x: Int) -> Int {
var f = 1
if x >= 2 {
for i in 2...x { f *= i }
}
return f
}
let n = 145
var total = 0
for c in String(n) {
total += factorial(Int(String(c))!)
}
print(total == n)
int factorial(int x) {
int f = 1;
for (int i = 2; i <= x; i++) f *= i;
return f;
}
void main() {
int n = 145;
int total = 0;
for (var d in n.toString().split('')) {
total += factorial(int.parse(d));
}
print(total == n);
}
#include <iostream>
#include <string>
using namespace std;
int factorial(int x) {
int f = 1;
for (int i = 2; i <= x; i++) f *= i;
return f;
}
int main() {
int n = 145, total = 0;
for (char c : to_string(n)) {
total += factorial(c - '0');
}
cout << (total == n ? "true" : "false") << endl;
return 0;
}
#include <stdio.h>
int factorial(int x) {
int f = 1;
for (int i = 2; i <= x; i++) f *= i;
return f;
}
int main() {
int n = 145, temp = n, total = 0;
while (temp > 0) {
total += factorial(temp % 10);
temp /= 10;
}
printf("%s\n", total == n ? "true" : "false");
return 0;
}