外星人计算圆周率的java改版

/**
* 采用展开的外星人算法求解PI
*
@author huxiao
*
* Pi =2 + 1/3(2 +2/5(2 + ...(n/2n+1)(2+ ......
*
*/


public class CalcPI {
public static final int MaxRound = 2000;
public static int[] PiArray = new int[MaxRound];
public static void CalcPi(int k)
{
int divide = 2*(MaxRound - k) + 3;
for(int i=1; i< MaxRound; i++ )
{
int relay = PiArray[i-1];
PiArray[i
-1] = relay / divide;
PiArray[i]
+= (relay % divide) * 10000;
}
int multi = MaxRound - k + 1;

for(int i = MaxRound-2; i>0; i--)
{
PiArray[i]
*= multi;
}
for(int i = MaxRound-2; i>0; i--)
{
PiArray[i
-1] += (PiArray[i])/10000;
PiArray[i]
= (PiArray[i])%10000;
}

PiArray[
0] += 2;
}

public static void main(String[] args){
PiArray[
0] = 2;
for(int k=1; k<=MaxRound; k++)
{
CalcPi(k);
}

java.text.DecimalFormat format
=new java.text.DecimalFormat("0000");

for(int i=0; i<MaxRound-1; i++)
{
System.out.print(format.format(PiArray[i]));
}
}
}
posted on 2011-03-17 22:48  FireWard  阅读(422)  评论(0编辑  收藏  举报