[Java] 纯文本查看 复制代码
import java.util.ArrayList;
import java.util.Iterator;
public class FractionSimple {
public static void main(String[] args) {
demo1();
demo2();
}
private static void demo2() {
Fraction f = new Fraction(241241242,235352);
long time1 = System.nanoTime();
for (int i=0;i<10000;i++){
f.simple();
}
long time2 = System.nanoTime();
System.out.println(time2 - time1);
time1 = System.nanoTime();
for (int i=0;i<10000;i++){
f.simple2();
}
time2 = System.nanoTime();
System.out.println(time2 - time1);
time1 = System.nanoTime();
for (int i=0;i<10000;i++){
f.simple3();
}
time2 = System.nanoTime();
System.out.println(time2 - time1);
}
private static void demo1() {
ArrayList<Fraction> list = new ArrayList<>();
list.add(new Fraction(1920,1080));
list.add(new Fraction(1600,900));
list.add(new Fraction(1440,900));
list.add(new Fraction(1366,768));
list.add(new Fraction(1360,768));
list.add(new Fraction(1280,800));
list.add(new Fraction(1280,768));
list.add(new Fraction(1280,720));
list.add(new Fraction(1024,768));
list.add(new Fraction(800,600));
Iterator<Fraction> it = list.iterator();
while (it.hasNext()) {
Fraction frac = it.next();
System.out.print(frac.numerator + " x " + frac.denominator);
System.out.println(" 的比例是:" + frac.simple3());
}
}
}
class Fraction {
int numerator;
int denominator;
Fraction (){
}
Fraction (int n, int d) {
numerator = n;
denominator = d;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public String simple() {
int a = numerator;
int b = denominator;
int c = a >b ? b:a; // 把 a和b 较小的数赋值给c
int i = 1;
while (i < c) {
if (a%i == 0 && b%i == 0) {
a = a / i;
b = b / i;
c = a < b ? a:b;
i = 1;
}
i++;
}
String str = a + " : " + b;
return str;
}
public String simple2() {
int a = numerator;
int b = denominator;
int c = a >b ? b:a; // 把 a和b 较小的数赋值给c
int i = c;
while (i > 0) {
if (a%i == 0 && b%i == 0) {
a = a / i;
b = b / i;
c = a < b ? a:b;
// i = 1;
}
i--;
}
String str = a + " : " + b;
return str;
}
public String simple3() {
int a = numerator;
int b = denominator;
int max;
int min;
int temp;
if (a > b){
max = a;
min = b;
}else {
max = b;
min = a;
}
while (min!=0) { // 循环结果max是最大公约数
temp = max%min;
max = min;
min = temp;
}
a = a / max;
b = b / max;
String str = a + " : " + b;
return str;
}
}