Skip to content

Instantly share code, notes, and snippets.

@grizmio
Created June 26, 2018 17:46
Show Gist options
  • Save grizmio/26f245d0c575001235c5a861b79f1297 to your computer and use it in GitHub Desktop.
Save grizmio/26f245d0c575001235c5a861b79f1297 to your computer and use it in GitHub Desktop.
Java: Tuple, Greatest Common Divisor and least Common Multiples exercises
package javaapplication4;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author grizmio
*/
public class JavaApplication4 {
public static void main(String[] args) {
System.out.println(leastCommonMultiple(5, 9));
System.out.println(leastCommonMultiple(15, 14));
System.out.println(leastCommonMultiple(2, 3));
System.out.println(leastCommonMultiple(2, 200));
System.out.println("--------");
System.out.println(multiplesTuples(6));
System.out.println(multiplesTuples(7));
System.out.println(multiplesTuples(9));
System.out.println("+++++++");
System.out.println(multiples(6));
System.out.println(multiples(7));
System.out.println(multiples(9));
System.out.println("Greatest common divisor: 3, 10: " + greatest_common_divisor(3, 10));
System.out.println("Greatest common divisor: 4, 10: " + greatest_common_divisor(4, 10));
}
public static int greatest_common_divisor(int x, int y){
int min = Math.min(x, y);
int max = Math.max(x, y);
List<Integer> max_mults = multiples(max);
List<Integer> min_mults = multiples(min);
for(int i: min_mults){
System.out.println(i);
if(max_mults.contains(i)){
return i;
}
}
return -1;
}
public static int leastCommonMultiple(int x, int y){
int mi = Math.min(x, y);
int ma = Math.max(x, y);
int p = ma;
for(;p%mi!=0;p+=ma){
}
return p;
}
public static List<Tuple<Integer, Integer> > multiplesTuples(int x){
/* devuelve:
(6) = [(1, 6), (2, 3), (3, 2), (6, 1)]
(7) = [(1, 7), (7, 1)]
(9) = [(1, 9), (3, 3), (9, 1)]
*/
List<Tuple<Integer, Integer> > mults_a = new ArrayList<>();
int last_greater = x;
for(int i=1; i <= x ; i++){
for(int d = 0 ; d <= last_greater ; d++){
if( i * d == x){
mults_a.add(new Tuple<>(i, d));
last_greater = d;
break;
}
}
}
return mults_a;
}
public static List<Integer> multiples(int x){
/* devuelve:
(6) = [6, 3, 2, 1]
(7) = [7, 1]
(9) = [9, 3, 1]
*/
List<Integer> mults_a = new ArrayList<>();
int last_greater = x;
for(int i=1; i <= x ; i++){
for(int d = 0 ; d <= last_greater ; d++){
if( i * d == x){
mults_a.add(d);
last_greater = d;
break;
}
}
}
return mults_a;
}
}
class Tuple<X, Y>{
private final X _x;
private final Y _y;
Tuple(X x, Y y){
_x = x;
_y = y;
}
X x(){
return _x;
}
Y y(){
return _y;
}
@Override
public String toString(){
return "(" + String.valueOf(_x) + ", " + String.valueOf(_y) + ")";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment