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

本文介绍了一种利用连分数求解佩尔方程最小正整数解的方法,并提供了一个Java实现示例。该算法适用于形式为x^2-Dy^2=1的方程,其中D为给定的非平方整数。通过不断迭代直至找到周期性规律,可以高效地计算出x和y的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

思路:

连分数法求,推荐一个博客https://blog.youkuaiyun.com/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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值