1. 问题描述
双色球中,红色球选号规则:红色球可以在1-33个编号中任意选择6个。
问题:红色球全部选中的概率为多少?
2. 代码:
package v1ch03.BigIntegerTest;
import java.math.*;
import java.util.*;
/**
* This program uses big numbers to compute the odds of winning the grand prize in a lottery.
* @version 1.20 2004-02-10
* @author Cay Horstmann
*/
public class BigIntegerTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you need to draw? ");
int k = in.nextInt();
System.out.print("What is the highest number you can draw? ");
int n = in.nextInt();
/*
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
*/
BigInteger lotteryOdds = BigInteger.valueOf(1);
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1)).divide(
BigInteger.valueOf(i));
System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
}
}
运行结果:
How many numbers do you need to draw? 6
What is the highest number you can draw? 33
Your odds are 1 in 1107568. Good luck!
即,红色球全部选中的概率为:1107568分之一(约111万分之一)。
另外,本程序也可以演示BigInterger类的强大之处,如下所示:
How many numbers do you need to draw? 500
What is the highest number you can draw? 5000
Your odds are 1 in 152383570502276241773112299038287011759805517717774989612063963324852197721349960590884233711082048864016759544054508257767390473359453022881045964121514812790325726285875069528156914452728158646183348385785484897051302963702456469661925649013938025675652103406710218905355077057732196294852278472953496440392540565238652496586095257231832780763525058654245376714838913660805861811146730935555609878975704618923988507281746376470494321008996284739018893410735106722857930028973378877130054931747509530956061693359470175950233574962808714004842287921921934995121777448532875190191549476629085646880295182806621692835943142454947817131669088583382928050125741393952210717943794438066831202814961683139272640. Good luck!
若在Excel中使用Combin()函数来计算,Combin(5000,500),将会发现溢出错误(#NUM)。而本程序的计算结果为705位数之多。至于最高支持多少位的计算,暂不深究,够用就行。