Home > database >  I am facing an error in the following java code can anyone help me out
I am facing an error in the following java code can anyone help me out

Time:12-19

class Solution {
  
    long  maxGcd(int  N) {
        long  a = (N * (N - 1))/ gcd(N,N-1);
        long  b = ((N-2)*(N-3))/ gcd(N-2,N-3);
        long  c = (a*b)/ gcd(a,b);
        long  num = N*(N-1);
        int count = 0;
        for (int i = N - 2; i >= 1; i--) {
            if (gcd(num, i) == 1) {
                num *= i;
                count  ;
            }
            if (count == 2) break;
        }
        return  Math.max(c, num);
    }

    long  gcd(long x, long y)
    {
        if(y==0)
        return x;
        return gcd(y,x*y);
    }
}

Error:

Exception in thread "main" java.lang.ArithmeticException: / by zero

I think I am getting this error because if, at some point, b=0 then c will be undefined. I tried changing it to

if(b!=0){
    long c =(a*b)/gcd(a,b)

but after running it, gives an error saying

prog.java:43: error: cannot find symbol
        return  Math.max(c, num);

Can anyone help me with the solution of this error?

Given an integer N. Find maximum LCM (Least Common Multiple) that can be obtained from four numbers less than or equal to N.
Note: Duplicate numbers can be used.

Example 1:

Input:
N = 4
Output: 12
Explanation:
The four numbers can be [4,4,3,2] or [4,4,4,3], etc. It can be shown that 12 is the maximum LCM of four numbers that can be obtained from numbers less than or equal to 4.

I have tried the above problem but it was giving me unexpected error.

CodePudding user response:

If I'm getting this right, it looks like there is a problem with your function "gcd": the recursive loop will never end

CodePudding user response:

If you divide some digit by 0 it will throw an error known as : java.lang.ArithmeticException

Solution

  1. try, catch block
  2. in catch block you can show msg to user ("Number cannot be divided by 0")
  • Related