Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
How to make this linear time complexity to log time complexity?

I was practising for a coding challenge and I got stuck up with this problem.

A and his friend bought a number each from the integer shop, A has number N and his friend has number M. A wants that both their numbers should be co-primes. To achieve this, A divides both the numbers by the largest number which can divide both the numbers. A wants to know the sum of numbers after doing this operation, help him find that sum.

Input

Input: 
N = 6, M = 5
Output: 
11
Explanation:
The largest number that can divide both 
5 and 6 is 1. 
After dividing, 5+6 = 11.

I have tried this code

long sum(long N, long M){
    long divider = 1;
    long min = Math.min(N,M);
    for(long i=2; i<=min; i++)
        if(N%i==0 && M%i==0)
            divider=i;
    return (N/divider) + (M/divider);
}

But the expected run-time complexity is O(log(n)). But my code gives O(n).

I'm not able to find any method to make it logarithmic. Please any help me. 😀😀

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You should use any efficient algorithm to find GCD - Greatest Common Divisor. E.g. you can try Euclidean algorithm with O(log(min(N, M)) time complexity.

public static long sum(long N, long M) {
    long gcd = gcdEuclideanAlgorithm(N, M);
    return (N / gcd) + (M / gcd);
}

private static long gcdEuclideanAlgorithm(long a, long b) {
    return b == 0 ? a : gcdEuclideanAlgorithm(b, a % b);
}

More algorithms you can find here.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda