Create function that calculates Java irreducible fraction

Asked

Viewed 503 times

1

I am developing a challenge in Java, and I need to create a function that calculates an irreducible fraction to solve the problem.

I created a function from some search but the function does not correctly calculate the value.

Would anyone know the problem with my job?

Follow below function code.

Java function

public void irreductibleFraction(int numerador, int denominador) 
    {
        int cont = 1;
        while ((numerador % cont == 0) && (denominador % cont == 0)) 
        {
            if(denominador != 0)
            {
                numerador /= cont;
                denominador /= cont;
                cont++;   
            }
            else
            {
                break;
            }

        }

        System.out.println(numerador + "/" + denominador);
}
  • What would be the expected value? Give an example pf.

  • 5

    Mathematically, the easiest way would be to divide both by MDC

  • 0/1 but returns me 1/0. With the numbers I am testing, which were made available by the challenge.

2 answers

1

I used recursiveness to make the code a little more readable

public static void reduzirFracao(int numerador,int denominador){
      
       int menor_numero = numerador < denominador ? numerador : denominador;
       
       for (int i = 2; i <= menor_numero; i++) {
           if(numerador % i == 0 && denominador % i == 0){
               reduzirFracao(numerador /i , denominador/i);
               return;
           }
       }

       System.out.println(numerador+"/"+denominador);

   }

0

One of the problems is that when you successfully perform an entire division (zero rest), you don’t try the same value again. For example, for 8/4 your program responds 4/2 because it is divided by 2 only once.

Another problem is its stopping condition. It stops the loop when two divisions occur successfully followed, which does not necessarily end the process.

I made a version of the function below.

public void irreductibleFraction(int numerador, int denominador) 
{
    int cont = 2;
    while (cont <= numerador && cont <= denominador) 
    {
        if(numerador % cont == 0 && denominador % cont ==0)
        {
            numerador /= cont;
            denominador /= cont;
        }
        else
        {
            cont++;
        }
    }

    System.out.println(numerador + "/" + denominador);
}
  • Keeps giving the same wrong result.

  • What values are going wrong?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.