1. 程式人生 > >ACM-ICPC 2018 焦作賽區網路預賽 J 大數開方

ACM-ICPC 2018 焦作賽區網路預賽 J 大數開方

題目連結

題意:給定一個數n,判斷nn(n1)/2是否是完全平方數

思路:
使用Java的BigInteger,對這兩個數開方以後,再對得到的數進行平方,判斷是否相等。

所以套上一個大數開方的模板即可。

程式碼:

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public
class Main { static Scanner cin; public static boolean check(BigInteger now){ if (now.compareTo(BigInteger.ZERO) == 0 || now.compareTo(BigInteger.ONE) == 0) return true; if (now.mod(BigInteger.valueOf(3)).compareTo(BigInteger.valueOf(2)) == 0) return false; String s = now.toString(); if
(s.length()%2==0) s = s.substring(0,s.length()/2+1); else s = s.substring(0,(1+s.length())/2); BigInteger res = BigInteger.ZERO; BigInteger m = new BigInteger(s); BigInteger two = new BigInteger("2"); if(s == "1") res = BigInteger.ONE; else
{ while(now.compareTo(m.multiply(m)) < 0){ m = (m.add(now.divide(m))).divide(two); } res = m; } if (res.multiply(res).compareTo(now) == 0) return true; return false; } public static void main(String argv[]){ cin = new Scanner(System.in); BigInteger n, m; int T = cin.nextInt(); while (T > 0) { T--; n = cin.nextBigInteger(); m = n.multiply(n.subtract(BigInteger.ONE)).divide(BigInteger.valueOf(2)); boolean flag1 = check(n), flag2 = check(m); if (flag1 && flag2) System.out.println("Arena of Valor"); else if (flag1) System.out.println("Hearth Stone"); else if (flag2) System.out.println("Clash Royale"); else System.out.println("League of Legends"); } } }