I have to write a recursive function the calculates the product of the digits of a number. What I wrote down is:
let rec digits_product x =
if x = 0 then 0
else
let n = x mod 10 in
n * digits_product (x / 10)
The problem is that it always returns me 0. I am sure there is something I miss out but I can not find out. Can you help me solve the problem? The code should calculate the product of the digits of a number, for example if I enter 12345 it should return 12345 which is equal to 120.
UPDATE
I changed the code to this:
let rec digits_product x =
match x with
| 0 -> 0
| 1 -> 1
| 2 -> 2
| 3 -> 3
| 4 -> 4
| 5 -> 5
| 6 -> 6
| 7 -> 7
| 8 -> 8
| 9 -> 9
| _ -> (x mod 10) * digits_product (x / 10)
It works right now, but I have another question: is there a more efficient way to do it?
Your code always makes a recursive call unless the parameter x
is 0. Since it doesn't show signs of infinite recursion, you know that it is returning 0 at least once. This should be enough to show what is wrong.
Update
You are checking the input for 0 because the answer is obvious in that case. But there are other inputs where the answer is obvious. I.e., where you don't need to do any multiplications to get the result. Why not check for all of these? You can check for all of these values with just one test.