POJ 2427 pell方程

简介:

题意:求解x^2-n*y^2=1的最小正整数解。

java大数模板。

import java.math.BigInteger;  
import java.util.Scanner;  

public class Main
{  
    public static void solve(int n) 
    {  
        BigInteger N, p1, p2, q1, q2, a0, a1, a2, g1, g2, h1, h2,p,q;  
        g1 = q2 = p1 = BigInteger.ZERO;  
        h1 = q1 = p2 = BigInteger.ONE;  
        a0 = a1 = BigInteger.valueOf((int)Math.sqrt(1.0*n));
        BigInteger ans=a0.multiply(a0);
        if(ans.equals(BigInteger.valueOf(n)))
        {
        	System.out.println("No solution!");
        	return;
        }
        N = BigInteger.valueOf(n);  
        while (true) 
        {  
            g2 = a1.multiply(h1).subtract(g1);     
            h2 = N.subtract(g2.pow(2)).divide(h1);  
            a2 = g2.add(a0).divide(h2);          
            p = a1.multiply(p2).add(p1);           
            q = a1.multiply(q2).add(q1);          
            if (p.pow(2).subtract(N.multiply(q.pow(2))).compareTo(BigInteger.ONE) == 0) break;
            g1 = g2;h1 = h2;a1 = a2;  
            p1 = p2;p2 = p;  
            q1 = q2;q2 = q;  
        }
        System.out.println(p+" "+q);
    }  
   
    public static void main(String[] args) 
    {  
        Scanner cin = new Scanner(System.in);  
        while(cin.hasNextInt())
        {
            solve(cin.nextInt());   
        }
    }  
}  


目录
打赏
0
0
0
0
1
分享
相关文章
POJ 2370 Democracy in danger(简单贪心)
Democracy in danger Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 3388   Accepted: 2508 Description In one of the...
974 0
poj supermaket (贪心)
http://poj.org/problem?id=1456 #include #include #include using namespace std; struct nod { int a; int d; }; bool cmp(nod x,nod y) { return x.
713 0
poj 2229 Sumsets 【动态规划】
点击打开题目 Sumsets Time Limit: 2000MS   Memory Limit: 200000K Total Submissions: 13291   Accepted: 5324 Description Far...
940 0
poj2031 kruskal
http://poj.org/problem?id=2031 #include<iostream> #include<algorithm> #include<cmath> #include<cstdio> using namespace std; double a[101][4]; double esp = 0.0000001;
1072 0
poj 1251 kruskal
http://poj.org/problem?id=1251 #include<algorithm> #include<iostream> #include<cstdlib> #include<cstdio> #include<cmath> using namespace std; #define maxm 205
1189 0
poj1861 kruskal
http://poj.org/problem?id=1861 #include<cstdio> #include<algorithm> #include<cstdlib> using namespace std; #define maxn 1001 #define maxm 15001 struct edge { int u,v
1292 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等