Smith's Problem POJ - 2427 【连分数求最小正整数解】

Smith's Problem POJ - 2427 【连分数求最小正整数解】

题意:求  $$ x^2+D*y^2 = 1 $$    的最小解。其实x取到最小的时候,y也取到最小。 双曲线画一画啦。

思路:

连分数法求,推荐一个博客https://blog.csdn.net/wh2124335/article/details/8871535?locationNum=14&fps=1

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

import java.math.*;


public class Main {
	static long [] a = new long [1000];
	static BigInteger x;
	static BigInteger y;
	public static void  main(String []args) {
		Scanner in=new Scanner(System.in);
		long n;
		while(in.hasNext()) {
			n=in.nextLong();
			if(pell_solution(n)) {
				System.out.println(x+" "+y);
			}
			else
				System.out.println("No solution!");
		}
	}
	
	public static boolean pell_solution(long D){
		double sq=Math.sqrt((double)D);
		long m=(long) Math.floor(sq);
		int i=0;
		if(m*m==D)return false;
		a[i++]=m;
		long b=m,c=1;
		double tmp;
		do{
			c=(D-b*b)/c;
			tmp=(sq+b)/c;
			a[i++]=(long)(Math.floor(tmp));
			b=a[i-1]*c-b;
		}while(a[i-1]!=2*a[0]);
		BigInteger p=new BigInteger("1");
		BigInteger q=new BigInteger("0");
		BigInteger t;
		for(int j=i-2;j>=0;j--){
			t=p;
			p=q.add(p.multiply(BigInteger.valueOf(a[j])));
			q=t;
		}
		if((i-1)%2==0){
			x=p;y=q;
		}else{
			x=BigInteger.valueOf(2).multiply(p).multiply(p).add(BigInteger.ONE);
			y=BigInteger.valueOf(2).multiply(p).multiply(q);
		}
		return true;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值