1. 程式人生 > >第一個java程式碼:華工校賽D:Lets Play Another Game

第一個java程式碼:華工校賽D:Lets Play Another Game

java大數(以下為轉)

JAVA之BigInteger

Java來處理高精度問題,相信對很多ACMer來說都是一件很happy的事,簡單易懂。用Java刷了一些題,感覺Java還不錯,在處理高精度和進位制轉換中,呼叫庫函式的來處理。下面是寫的一些Java中一些基本的函式的及其……

標頭檔案:import java.io.*;

import java.util.*;

import java.math.*;

讀入: Scanner cin = Scanner (System.in);

while(cin.hasNext())//等價於!=EOF

n=cin.nextInt();//讀入一個int型的數

n=cin.nextBigInteger();//讀入一個大整數

輸出: System.out.print(n);//列印n

System.out.println();//換行

System.out.printf("%d\n",n);//也可以類似c++裡的輸出方式

定義: int i,j,k,a[];

a = new int[100];

BigInteger n,m;

BigDecimal n;

String s;

資料型別:

資料型別 型別名 位長 取值範圍 預設值

布林型 boolean 1 true,false false

位元組型 byte 8 -128-127 0

字元型 char 16 ‘\u000’-\uffff ‘\u0000’

短整型 short 16 -32768-32767 0

整型 int 32 -2147483648,2147483647 0

長整型 long 64 -9.22E18,9.22E18 0

浮點型 float 32 1.4E-45-3.4028E+38 0.0

雙精度型 double 64 4.9E-324,1.7977E+308 0.0

這裡特別要提出出的兩種型別:

BigInteger 任意大的整數,原則上是,只要你的計算機的記憶體足夠大,可以有無限位的

BigInteger 任意大的實數,可以處理小數精度問題。

BigInteger中一些常見的函式:

A=BigInteger.ONE

B=BigInteger.TEN

C=BigInteger.ZERO

一些常見的數的賦初值。將int型的數賦值給BigInteger,BigInteger.valueOf(k);

基本的函式:

valueOf:賦初值

add:+ a.add(b);

subtract:-

multiply:*

divide:/

remainder:this % val

divideAndRemainder:a[0]=this / val; a[1]=this % val

pow:a.pow(b)=a^b

gcd,abs:公約數,絕對值

negate:取負數

signum:符號函式

mod:a.mod(b)=a%b;

shiftLeft:左移,this << n ,this*2^n;

shiftRight:右移,this >> n,this/2^n;

and:等同於c++的&&,且;

or:||,或;

xor:異或,BigInteger xor(BigInteger val),this^val

not:!,非;

bitLength:返回該數的最小二進位制補碼錶示的位的個數,即 *不包括* 符號位 (ceil(log2(this <0 ? -this : this + 1)))。對正數來說,這等價於普通二進位制表示的位的個數。

bitCount:返回該數的二進位制補碼錶示中不包擴符號位在內的位的個數。該方法在 BigIntegers 之上實現位向量風格的集合時很有用。

isProbablePrime:如果該 BigInteger 可能是素數,則返回 true ;如果它很明確是一個合數,則返回 false 。 引數 certainty 是對呼叫者願意忍受的不確定性的度量:如果該數是素數的概率超過了 1 - 1/2**certainty方法,則該方法返回 true 。執行時間正比於引數確定性的值。

compareTo:根據該數值是小於、等於、或大於 val 返回 -1、0 或 1;

equals:判斷兩數是否相等,也可以用compareTo來代替;

min,max:取兩個數的較小、大者;

intValue,longValue,floatValue,doublue:把該數轉換為該型別的數的值。

今天參考課本寫了一個關於二進位制與十進位制轉換的程式,程式演算法不難,但寫完後測試發現不論是二轉十還是十轉二,對於大於21億即超過整數範圍的數不能很好的轉換。都會變成0.
參考書籍發現使用使用BigInteger可以解決這個問題。
於是查找了下JDK,然後測試幾次終於寫成功了!
使用心得如下:

1,BigInteger屬於java.math.BigInteger,因此在每次使用前都要import 這個類。偶開始就忘記import了,於是總提示找不到提示符。

2,其構造方法有很多,但現在偶用到的有: BigInteger(String val)
將 BigInteger 的十進位制字串表示形式轉換為 BigInteger。
BigInteger(String val, int radix)
將指定基數的 BigInteger 的字串表示形式轉換為 BigInteger。
如要將int型的2轉換為BigInteger型,要寫為BigInteger two=new BigInteger("2"); //注意2雙引號不能省略

3,BigInteger類模擬了所有的int型數學操作,如add()==“+”,divide()==“-”等,但注意其內容進行數學運算時不能直接使用數學運算子進行運算,必須使用其內部方法。而且其運算元也必須為BigInteger型。
如:two.add(2)就是一種錯誤的操作,因為2沒有變為BigInteger型。

4,當要把計算結果輸出時應該使用.toString方法將其轉換為10進位制的字串,詳細說明如下:
String toString()
返回此 BigInteger 的十進位制字串表示形式。
輸出方法:System.out.print(two.toString());

5,另外說明三個個用到的函式。 BigInteger remainder(BigInteger val)
返回其值為 (this % val) 的 BigInteger。
BigInteger negate()
返回其值是 (-this) 的 BigInteger。
int compareTo(BigInteger val)
將此 BigInteger 與指定的 BigInteger 進行比較。
remainder用來求餘數。
negate將運算元變為相反數。
compare的詳解如下:

compareTo
public int compareTo(BigInteger val)將此 BigInteger 與指定的 BigInteger 進行比較。對於針對六個布林比較運算子 (<, ==, >, >=, !=, <=) 中的每一個運算子的各個方法,優先提供此方法。執行這些比較的建議語句是:(x.compareTo(y) <op> 0),其中 <op> 是六個比較運算子之一。
指定者:
介面 Comparable<BigInteger> 中的 compareTo
引數:
val - 將此 BigInteger 與之比較的 BigInteger。
返回:

將BigInteger的數轉為2進位制:

public class TestChange {
public static void main(String[] args) {
System.out.println(change("3",10,2));
}
//num 要轉換的數 from源數的進位制 to要轉換成的進位制
private static String change(String num,int from, int to){
return new java.math.BigInteger(num, from).toString(to);
}
}


Problem D: Lets Play Another Game

Description

OK, if you finished previous game, lets play another game :D

Now n participants of this game sit around the table. Each minute one pair of neighbors can change their places. Find the minimum time (in minutes) required for all participants to sit in reverse order (so that left neighbors would become right, and right - left).

Input

The first line is the amount of tests. Each next line contains one integer n (1 <= n <= 1e18) - the amount of participants.

Output

For each number n of participants to game print on the standard output, on a separate line, the minimum time required for all participants to sit in reverse order.

Sample Input

3456

Sample Output

246

這題通過找規律得出公式,重點在於大數

具體程式碼:

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

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        
        Scanner sb=new Scanner(System.in);
        int test;
        test=sb.nextInt();
        
        BigInteger one=BigInteger.ONE;
            BigInteger zero=one.subtract(one);
        BigInteger two=one.add(one);
          BigInteger three=two.add(one);
             BigInteger four=three.add(one);
        while(test-->0)
        {
          BigInteger n=sb.nextBigInteger();
          BigInteger sum;
          if(n.mod(two).compareTo(one)==0)
          {
              BigInteger xiang=n.subtract(one).divide(two);
              sum=xiang.add(xiang.multiply(xiang.subtract(one)));
              
        }
          else    
          {            
               BigInteger xiang=n.subtract(two).divide(two);
               if(xiang.mod(two).compareTo(zero)==0)
               {
                   BigInteger sbb=xiang.divide(two);
                       // System.out.println(sbb);
                   sum=sbb.multiply(three).add(sbb.multiply(sbb.subtract(one).multiply(two)));
                        //.out.println(sum);
               sum=sum.multiply(two);
                   // System.out.println(sum);
               }
               else
               {
                   BigInteger sbb=xiang.divide(two);
                    // System.out.println(sbb);
                   sum=sbb.multiply(three).add(sbb.multiply(sbb.subtract(one).multiply(two)));
                    // System.out.println(sum);
                             sum=sum.multiply(two);
                         //      System.out.println(sum);
                             BigInteger kk=xiang.divide(two).multiply(four).add(three);
                           //    System.out.println(kk);
                             sum=sum.add(kk).subtract(one);    
                           //    System.out.println(sum);
               }
            }
          System.out.println(sum);
               
          }
        
      
      
    }
    
}