NBUT1224 Happiness Hotel

不知道哪里来的一个什么OJ上的题,

考的是一个叫做pell方程的东西

x^2-ky^2=1

求这个东西的最小的解

无意中翻数学模板翻到的这个

本来用C++写的,但是最后的结果会爆long long

所以用JAVA写了

但是用Java写了之后又发现,,,,,这个奇葩OJ根本不能用Java交,

考虑到输入总共才1000,所以就强行把Java的运算结果打到表里,然后在用C++交上去

其实主要是拿个模板啦

 

下面就是用Java进行打表的程序

///获得了Java文件重定向输入的技能

///获得了大数开根号的技能

///获得了pell方程求解的技能

 1 import java.io.*;
 2 import java.util.*;
 3 import java.math.*;
 4 
 5 public class Main{
 6 
 7     public static BigInteger[] pell(BigInteger n){///求解pell方程,返回两个大数,即一个两个元素的大数数组,分别为x和y
 8         ///x^2-ky^2=1
 9         BigInteger[]p = new BigInteger[10];
10         BigInteger[]q = new BigInteger[10];
11         BigInteger[]h = new BigInteger[10];
12         BigInteger[]g = new BigInteger[10];
13         BigInteger[]a = new BigInteger[10];
14         p[0] = BigInteger.ZERO;q[0] = BigInteger.ONE;
15         p[1] = BigInteger.ONE;q[1] = BigInteger.ZERO;
16         a[0] = sqrt(n);
17         a[2] = a[0];
18         g[1] = BigInteger.ZERO;h[1] = BigInteger.ONE;
19         while(true){
20             g[2] = a[2].multiply(h[1]).subtract(g[1]);
21             h[2] = n.subtract(g[2].multiply(g[2])).divide(h[1]);
22             a[3] = g[2].add(a[0]).divide(h[2]);
23             p[2] = a[2].multiply(p[1]).add(p[0]);
24             q[2] = a[2].multiply(q[1]).add(q[0]);
25             if(p[2].multiply(p[2]).subtract(n.multiply(q[2].multiply(q[2]))).equals(BigInteger.ONE)==true&&p[2].equals(BigInteger.ZERO)==false&&q[2].equals(BigInteger.ZERO)==false)
26             return new BigInteger[] {p[2],q[2]};
27             g[0] = g[1];h[0] = h[1];
28             g[1] = g[2];h[1] = h[2];
29             a[2] = a[3];
30             p[0] = p[1];p[1] = p[2];
31             q[0] = q[1];q[1] = q[2];
32         }
33 
34     }
35 
36     static BigInteger sqrt(BigInteger n){///对于大数开根号
37         BigInteger low = BigInteger.ZERO,high = n,ans = null;
38         while(low.compareTo(high)<=0){
39             BigInteger mid = low.add(high).shiftRight(1);
40             if(mid.multiply(mid).compareTo(n)<=0){
41                 ans = mid;
42                 low = mid.add(BigInteger.ONE);
43             }
44             else high = mid.subtract(BigInteger.ONE);
45         }
46         return ans;
47     }
48     public static void main(String[]args) throws IOException {///这个不知道是扔什么的意思的一句话,必须要写
49         System.setIn(new BufferedInputStream(new FileInputStream("in.txt")));///文件重定向输入
50         System.setOut(new PrintStream(new FileOutputStream("out.txt")));   ///文件重定向输出
51         Scanner cin = new Scanner(new BufferedInputStream(System.in));
52         while(cin.hasNext()){
53             int n = cin.nextInt(),ok = 1;
54             for(int i = 1;i<=31;++i)
55                 if(i*i==n){ok = 0;break;}
56             if(ok==0){System.out.println(-1);continue;}
57             BigInteger r[] = pell(BigInteger.valueOf(n));
58             System.out.println(r[0]);
59         }
60     }
61 }

 

posted on 2015-08-18 18:42  round_0  阅读(220)  评论(0编辑  收藏  举报

导航