Sum of digit's factorial

In order to answer the 34th question from Project Euler (http://projecteuler.net/problem=34), I wrote these two functions :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include "math.h"
using namespace std;

long factorial(long n){
    if (n == 0 || n == 1) {
        return 1;
    }else{
        return n*factorial(n-1);
    }
    throw "factorial error";
}

long factorialSum(long n){
    
    long sum = 0, N = ceil(log10(n)) , num[(int)N];;
    
    for (int i = 0; i < N; i++){
        num[i] = (n/10 - floor(n/10)) * 10;
        n = floor(n/10);
        sum += factorial(num[i]);
        cout << num[i];
    }
    cout << endl;
    return sum;
    
}


The problem is in the factorialSum() function. For any number, the functions shows the digits as "0"s hence the result is the number of digits. I can't see where the error is. Any suggestion?




Last edited on
num[i] = (n/10 - floor(n/10)) * 10;
n/10 always equals to floor(n/10)

What you want to do there is to extract the last digit of n right? Then use modulus operator num[i] = n%10;


* n = floor(n/10); is ugly, n /= 10; instead
Thanks a lot this solved the problem but why n/10 always equals to floor(n/10)?
because in C++ integer division always discards the fractional part, hence it always equal to floor which also removes the fractional part.
to avoid integer division, use n/10.0 or, if both operands are variables: static_cast<double>(n)/m
Topic archived. No new replies allowed.