(Coderbyte) Division - Solução

Have the function Division(num1,num2) take both parameters being passed and return the Greatest Common Factor. That is, return the greatest number that evenly goes into both numbers with no remainder. For example: 12 and 16 both are divisible by 1, 2, and 4 so the output should be 4. The range for both parameters will be from 1 to 10^3.

* Esta é uma solução alternativa à solução que seria comum. Não funciona para números negativos, mas resolve o problema proposto. Este problema também poderia ter sido resolvido usando outros algoritmos mais eficientes para calcular o Máximo Divisor Comum (MDC).


import java.util.*;
import java.io.*;

class Function { 
  int Division(int num1, int num2) {
    int menor;
   
    if (num1 < num2) {
      menor = num1;
    }
    else {
      menor = num2;
    }
   
    for (int i = menor; i >= 1; i--) {
      if (num1%i == 0 && num2%i == 0) {
        return i; 
      }
    }
      
    return 1;
   
  }
 
  public static void main (String[] args) { 
    // keep this function call here    
    Scanner  s = new Scanner(System.in);
    Function c = new Function();
    System.out.print(c.Division(s.nextLine()));
  }  
 
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução