Anshul Dayavaan
Anshul Dayavaan

Reputation: 19

I get a stack overflow error for this code:

I am a newbie in java and I don't know why this code gives a stack overflow error....

int lcm = 0;
public int a (int n1,int n2) {

     n1 = 6;
     n2 = 5;
    if(n1>n2) {
        lcm = n1;
    }
     else if(n2>n1) {
        lcm = n2;
    }
        if(lcm%n1 == 0 && lcm%n2 == 0) {
            lcm = lcm;            
        }
        else {
            ++lcm;
            a(6,5);
    }
    return (lcm);
}
 public static void main (String[] args) {

    ktm ob = new ktm();
    int ans = ob.a(6,5);
    System.out.println(ans);

}

I expect to calculate the lcm of two numbers using recursion but it gives me this error message : java.lang.StackOverflowError at ktm.a(ktm.java:25)

Upvotes: 0

Views: 75

Answers (2)

Jeet Raythatha
Jeet Raythatha

Reputation: 11

function solution(a,b){

    function gcd(a,b){
    
        while(b){
          [a,b]=[b,a%b];
          return b;
        }
    }
    function lcm(a,b){
      return a*b/gcd(a,b);
    
    }
return lcm(a,b);

}

var res = solution(20,15);
console.log(res);

Here is a function gcd in above javascript snippet in that we have swapped values using destructuring concept of ES6. Then again a function lcm that returns both numbers multiplication and divide it by calling gcd(a,b)

Upvotes: 0

Rutvik Joshi
Rutvik Joshi

Reputation: 107

You are always sending 6 and 5 as a input to your function, which makes your function in a infinite call for that input because the if condition (lcm%n1 == 0 && lcm%n2 == 0) will not satisfy for the given input.

  • If you want to use recursion to calculate LCM than try this

    int gcd(int a, int b) 
    { 
    if (a == 0) 
        return b;  
    return gcd(b % a, a);  
    } 
    
    int lcm(int a, int b) 
    { 
        return (a*b)/gcd(a, b); 
    } 
    public static void main (String[] args) {
      ktm ob = new ktm();
      int ans = ob.lcm(6,5);
      System.out.println(ans);
    }
    

Upvotes: 1

Related Questions