Java源码——使用BigInteger计算组合数(彩票中奖概率计算示例)

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位数之多。至于最高支持多少位的计算,暂不深究,够用就行。
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值