Here's my code:
Code:
import java.util.ArrayList;
public class ContFracSqrt {
static boolean v=true; // verbosity
public static void main(String[] args) {
print(cfe(5));
}
static void print(ArrayList<Integer> a) {
int i;
String s=a.toString();
if(a.size()>1)
for(i=2;;i++)
if(s.charAt(i)==',') {
s=s.substring(0,i)+"; ("+s.substring(i+2);
s=s.substring(0,s.length()-1)+")]";
break;
}
System.out.println(s);
}
static ArrayList<Integer> cfe(int n) {
ArrayList<Integer> x=new ArrayList<Integer>();
int a=(int)Math.sqrt(n),b=a,c=1,d,e,f,g;
x.add(a);
if(a*a==n) return x;
if(v) System.out.println("\\sqrt{"+n+"}="+a+"+\\dfrac{\\sqrt{"+n+"}-"+a+"}{1}");
if(v) System.out.print("\\dfrac{1}{\\sqrt{"+n+"}-"+a+"}=");
while(true) {
d=c;
c=n-b*b;
g=gcd(c,d);
c/=g;
d/=g;
b=-b;
f=a-c;
for(e=0;b<=f;e++)
b+=c;
x.add(e);
if(v) System.out.println(e+"+\\dfrac{\\sqrt{"+n+"}-"+b+"}{"+c+"}");
if(b==a&&c==1) return x;
if(v) System.out.print("\\dfrac{"+c+"}{\\sqrt{"+n+"}-"+b+"}=");
}
}
static int gcd(int a,int b) {
return (b==0)?a:gcd(b,a%b);
}
}
Which gives output for :
and for :
Let me know how this works for you. I decided against ASCII mode since LaTeX is so much nicer.