I have been experimenting with Python as a beggar in the last few hours. I wrote a recursive function that returns recurse (x) as x! in Python and Java to compare them. The two parts of the code are identical, but for some reason Python works, but Java does not. In Python, I wrote:
x = int(raw_input("Enter: ")) def recurse(num): if num != 0: num = num * recurse(num-1) else: return 1 return num print recurse(x)
If the variable num is multiplied by num-1, until it reaches 0, and prints the result. In Java, the code is very similar, only longer:
public class Default { static Scanner input = new Scanner(System.in); public static void main(String[] args){ System.out.print("Enter: "); int x = input.nextInt(); System.out.print(recurse(x)); } public static int recurse(int num){ if(num != 0){ num = num * recurse(num - 1); } else { return 1; } return num; }
}
If I enter 25, the Python code returns 1.5511x10E25, which is the correct answer, but the Java code returns 2,076,180,480, which is not the correct answer, and I'm not sure why.
Both codes work on the same process:
- Make sure num is zero
- If num is not equal to zero
- num = num times recursion num - 1
- If num is zero
- Returns 1, ending this recursion call stack and calling each returned number to start the multiplication
- return num
There are no brackets in python; I thought I somehow changed the situation, so I removed the brackets from the Java code, but that did not change. Changing the logical (num! = 0) to (num> 0) did not change anything. Adding an if statement to else provided more context, but the value was the same anyway.
Printing num values ββat each point gives an idea of ββhow the function goes wrong:
Python:
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800 87178291200 1307674368000 20922789888000 355687428096000 6402373705728000 121645100408832000 2432902008176640000 51090942171709440000 1124000727777607680000 25852016738884976640000 620448401733239439360000 15511210043330985984000000 15511210043330985984000000
Constant increase. In Java:
1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 1932053504 1278945280 2004310016 2004189184 -288522240 -898433024 109641728 -2102132736 -1195114496 -522715136 862453760 -775946240 2076180480 2076180480
Steady growth. In fact, num returns negative numbers, as if the function returns negative numbers, even if the number should not go below zero.
Both Python and Java codes work on the same procedure, but they return completely different values. Why is this happening?