1. 程式人生 > >Heron and His Triangle HDU

Heron and His Triangle HDU

部落格目錄

原題

題目傳送門

A triangle is a Heron’s triangle if it satisfies that the side lengths of it are consecutive integers t−1, t, t+ 1 and thatits area is an integer. Now, for given n you need to find a Heron’s triangle associated with the smallest t bigger  than or equal to n.

Input

The input contains multiple test cases. The first line of a multiple input is an integer T (1 ≤ T ≤ 30000) followedby T lines. Each line contains an integer N (1 ≤ N ≤ 10^30). 

Output

For each test case, output the smallest t in a line. If the Heron’s triangle required does not exist, output -1.

Sample Input

4
1
2
3
4

Sample Output

4
4
4
4

題意

給出一個n,找到最小的一個t使得:t>=n

且以長度為t-1 ,t ,t+1的三條邊構成的三角形面積為整數。

輸出t。

規律:打表可得在2e7範圍內滿足上述條件的t有

 4,14,52,194,724,2702,10084,37634

然後有 t[i]=4*t[i-1]-t[i-1];

然後菜雞現學現賣java大數(因為這一場有個簽到題是自己手寫的大數加法,然後用c++寫了半天發現要改成減法還是要費一段功夫,就有點慫換java)

AC程式碼

//package learn1;

import java.util.*; import java.math.*; public class Main {     public static BigInteger co[]=new BigInteger[200];     public static void main(String[] args) {         // TODO 自動生成的方法存根         Scanner cin = new Scanner(System.in);         int T;         T=cin.nextInt();         BigInteger n; // 4,14,52,194,724,2702,10084,37634         co[0]=new BigInteger("4");//("4");         co[1]=new BigInteger("14");         for(int i=2;i<=180;i++){  //我們發現第180多個已經很大很大夠用了。             co[i]=co[i-1].multiply(co[0]);             co[i]=co[i].subtract(co[i-2]);         }         while(T-->0){             n=cin.nextBigInteger();             for(int i=0;;i++){                 if(n.compareTo(co[i])<=0){                     System.out.println(co[i].toString());                     break;                 }             }         }     }

}