# Return to Revisions

8 of 8 added 3 characters in body

# Java - 278

import java.math.*;void m(String a){BigInteger i=null;BigInteger n=i.ONE;BigInteger d=n.add(n);BigInteger e=n;for(i=e;i.compareTo(i.valueOf(Integer.parseInt(a[0])))<0;i=i.add(e))do if((n=n.add(e)).compareTo(d)>=0)d=d.add(n=e);while(!n.gcd(d).equals(e));System.out.print(n+"/"+d);}}


Ungolfed:

import java.math.*;
void m(String args[]){
BigInteger i=null;
BigInteger n=i.ONE;
BigInteger d=n.add(n);
BigInteger e=n;
for(i=e; i.compareTo(i.valueOf(Integer.parseInt(args[0])))<0; i=i.add(e))
do
if((n=n.add(e)).compareTo(d)>=0)
d=d.add(n=e);
while(!n.gcd(d).equals(e));
System.out.println(n +"/"+d);
}
}


### Original version

I have made no attempt to arbitrarily extend this solution. Not sure if that will gain me or lose me points. It is, however, a correct solution that will work for very large numbers.

public class Test {

static class Fractions implements Iterator<String> {

// Start at 1.
BigInteger numerator = BigInteger.ONE;
// Start at 2.
BigInteger denominator = BigInteger.ONE.add(BigInteger.ONE);

@Override
public boolean hasNext() {
// Never ending!
return true;
}

@Override
public String next() {
String next = numerator + "/" + denominator;
do {
// Keep selecting the next one.
step1();
// Until they are relatively prime.
} while (!numerator.gcd(denominator).equals(BigInteger.ONE));
return next;
}

private void step1() {
// Take a single step.
numerator = numerator.add(BigInteger.ONE);

if (numerator.compareTo(denominator) >= 0) {
// num >= den - step denom up and num rewinds to 1.
numerator = BigInteger.ONE;
denominator = denominator.add(BigInteger.ONE);
}
}

}

// Returns the nth fraction.
public String nthFraction(BigInteger n) {
Iterator<String> f = new Fractions();
for (BigInteger i = BigInteger.ONE; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
f.next();
}
return f.next();
}

// Returns the nth fraction.
public String nthFraction(long n) {
return nthFraction(BigInteger.valueOf(n));
}

public void test() {
Iterator<String> f = new Fractions();
for (int i = 1; i < 100; i++) {
System.out.println(i + "=" + f.next());
}
}

public static void main(String args[]) {
try {
//new Test().test();
if (args.length >= 1) {
System.out.println(new Test().nthFraction(Integer.parseInt(args[0])));
} else {
System.out.println(new Test().nthFraction(5));
}
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
}

 answered Sep 15 '14 at 14:14 OldCurmudgeon 23922 silver badges77 bronze badges