NBUT1224 Happiness Hotel

不知道哪裏來的一個什麼OJ上的題,java

考的是一個叫作pell方程的東西數組

x^2-ky^2=1ide

求這個東西的最小的解spa

無心中翻數學模板翻到的這個code

原本用C++寫的,可是最後的結果會爆long longblog

因此用JAVA寫了ip

可是用Java寫了以後又發現,,,,,這個奇葩OJ根本不能用Java交,ci

考慮到輸入總共才1000,因此就強行把Java的運算結果打到表裏,而後在用C++交上去數學

其實主要是拿個模板啦io

 

下面就是用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 }
相關文章
相關標籤/搜索