My father and I were writing programs to find numbers that are equal to the sum of the factorial of the digits. For example, 145 = 1! + 4! + 5!. We wrote three programs one in Python, one in Java and one in C++. The ones in Java and C++ ran in about 7.3 seconds while the one in Python ran in about 7 minutes. I was wondering why this is. I've posted the Python and C++ code, I will post the Java code if you desire.
("... " = tab)
Code:
Code:
So far the numbers we have come up with are: 1, 2, 145, and 40585.
("... " = tab)
Code:
# build a table of factorials 0! through 9!
lastfact = 1
fact = [1]
for k in range(1,10):
... lastfact *= k
... fact.append(lastfact)
# function to calculate the sum of the factorials of the digits
def factsum(n):
... if n==0:
... ... return 1
... ans = 0
... while n>0:
... ... u = n % 10
... ... ans += fact[u]
... ... n -= u
... ... n /= 10
... return ans
# check the numbers up to 100 million
for k in xrange(100*1000*1000):
... if k == factsum(k):
... ... print k
Code:
#include <iostream>
using namespace std;
/// Stopping point of our search
const long LAST = 100*1000*1000
/// Table of factorials
void init_ftable() {
... ftable = new long[10]
... ftable[0] = 1
... for(int k=1; k<=9; ++k) {
... ... ftable[k] = ftable[k-1] * k;
... }
}
/// Compute sum of factorials of the digits
long fsum(long n) {
... if (n==0) return 1;
... long ans = 0;
... while (n>0) {
... ... int u = n % 10;
... ... ans += ftable[u];
... ... n -= u;
... ... n /= 10;
... }
... return ans;
}
int main() {
... init_ftable();
... for(int n=1; n<=LAST; ++n) {
... ... if (fsum(n) == n) {
... ... ... cout << n << endl;
... ... }
... }
}
So far the numbers we have come up with are: 1, 2, 145, and 40585.