1. 程式人生 > >hdu6222(遞推規律+java大數)

hdu6222(遞推規律+java大數)

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
Source 題意:讓你找這樣的一個三角形,三條邊為t,t-1,t+1,並且面積為整數,最後滿足t大於等於n。 思路:暴力打表找規律。 暴力打表程式碼:
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while(scanf("%d", &n) != EOF)
    {
        for(int i = 4; i <= 10000; i++)
        {
            int p = (3 * i) / 2;
            int area = p * (p - i - 1) * (p - i + 1) * (p - i);
            bool flag = false;
            for(int j = 1; j <= sqrt(area) + 1; j++)
            {
                if(j * j == area && i >= n)
                {
                    flag = true;
                    printf("%d\n", i);
                    break;
                }
            }
            if(flag) break;
        }
    }
    return 0;
三角形面積公式:formula    其中P為三角形的半周長。(海倫公式) 打個表之後發現這樣一些數字4,14,52,194,724,2702....然後得出遞推式子,F[n]=4*F[n-1]-F[n-2];由於n非常的大,所以矩陣快冪維護也不行。最後考慮這樣的數字幾乎增長比較快,那麼範圍內這樣的數字就會比較少,不想用高精度的可以考慮用java大數了,用個list將所有n範圍內的結果儲存一下,最後直接查詢就可以了。 程式碼:
import java.util.*;
import java.math.*;
public class Main{
    public static void main
(String[] args){ BigInteger x=BigInteger.valueOf(4); BigInteger y=BigInteger.valueOf(14); List<BigInteger> list=new ArrayList <>(); list.add(x); list.add(y); BigInteger t; while(y.compareTo(BigInteger.TEN.pow(30))<=0){ BigInteger num2=BigInteger.valueOf(4); t=y; y=num2.multiply(y).subtract(x); list.add(y); x=t; } Scanner cin=new Scanner(System.in); int T=cin.nextInt(); while(T-->0){ BigInteger n=cin.nextBigInteger(); for(BigInteger xx:list){ if(n.compareTo(xx)<=0) { System.out.println(xx); break; } } } } }