1. 程式人生 > >Game of Taking Stones(java大數高精度)

Game of Taking Stones(java大數高精度)

Two people face two piles of stones and make a game. They take turns to take stones. As game rules, there are two different methods of taking stones: One scheme is that you can take any number of stones in any one pile while the alternative is to take the same amount of stones at the same time in two piles. In the end, the first person taking all the stones is winner. Now, giving the initial number of two stones, can you win this game if you are the first to take stones and both sides have taken the best strategy? Input Input contains multiple sets of test data.Each test data occupies one line, containing two non-negative integers a and b, representing the number of two stones. a and b are not more than 10100 . Output For each test data, output answer on one line. ‘1’ means you are the winner, otherwise output ‘0’. Sample Input 2 1 8 4 4 7 Sample Output 0 1 0

思路:

一個裸的威佐夫博奕,不過精度要求高需要用到牛頓迭代來求根號5.

程式碼:

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Scanner cin=new Scanner(System.in);
		BigInteger a,b;
		//求解高精度根號5
		BigDecimal x=new BigDecimal("2");
		for(int i=1;i<=100;i++)
		{
			BigDecimal x1=(x.multiply(x)).subtract(new BigDecimal("5"));
			BigDecimal x2=x.multiply(new BigDecimal(2));
			BigDecimal x3=x1.divide(x2, 120, BigDecimal.ROUND_HALF_DOWN);
			x=x.subtract(x3);
		}
		
		BigDecimal xx=(x.add(new BigDecimal(1))).divide(new BigDecimal(2));
		
		while(cin.hasNext())
		{		
			a=cin.nextBigInteger();
			b=cin.nextBigInteger();
			//威佐夫博奕模板
			if(a.compareTo(b)==1)
			{
				BigInteger c;
				c=a;
				a=b;
				b=c;
			}
			String s=b.subtract(a).toString();
			BigDecimal k=new BigDecimal(s);
			BigDecimal sum1=k.multiply(xx);
			BigDecimal sum2=sum1.add(k);
			String s1=sum2.toString();
			String[] s2=s1.split("\\.");
			BigInteger t=new BigInteger(s2[0]);
			if(t.equals(b))
			{
				System.out.println(0);
			}
			else
			{
				System.out.println(1);
			}
			}
	}
}