The Java program functions correctly using iteration and recursion. But for some strange reason I can't understand is that when the numbers I enter with anything above 9200 I get a StackOverFlow. I tried changing to a long but that's all I could think of. Any idea as to how and why this is happening and how do I fix is so that it can calculate any number?
import java.util.Scanner;
public class Multiplication {
public static long multiIterative(long a, long b) {
long result = 0;
while (b > 0) {
result += a;
b--;
}
return result;
}
public static long multiRecursive(long a, long b) {
if (a == 0 || b == 0) {
return 0;
}
return a + multiRecursive(a, b - 1);
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter first Integer: ");
long a = userInput.nextInt();
System.out.print("Please enter second Integer: ");
long b = userInput.nextInt();
System.out.println("The Multiplication Iteration would be: " + multiIterative(a, b));
System.out.println("The Multiplication Recursion would be: " + multiRecursive(a, b));
}
}