高精度运算——大数阶乘、排列、组合

本文介绍了一个用于高精度计算阶乘、排列和组合的方法,通过自定义类HighPrecision实现连乘、求阶乘、求排列与求组合的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package org.sugite.tools;

import java.util.Arrays;

/*
 *	@topic:求1000以内的阶乘、排列、组合
 */
public class HighPrecision {
	private static int[] a = new int[2570];// 存放被乘数与最后的乘积
	private static int[] b = new int[2570];// 存放除法过程中的商
	private static int k, s, i, j, w;// k为a中的位数,w为进位值,s为余数

	public static void main(String[] args) throws Exception {
		// System.out.println("Hello Landor!");
//		factorial(1000);
//		for (i = k; i > 0; i--) {
//			System.out.print(a[i]);
//		}
	}

	/* 求阶乘方法 */
	public static int[] factorial(int n) throws Exception {
		Arrays.fill(a, 0);
		cumprod(n, 2);
		return a;
	}

	/* 求排列方法 */
	public static int[] arrangement(int m, int n) throws Exception {
		Arrays.fill(a, 0);
		cumprod(m, m - n + 1);
		return a;
	}

	/* 求组合方法 */
	public static int[] combination(int m, int n) throws Exception {
		Arrays.fill(a, 0);
		Arrays.fill(b, 0);
		cumprod(m, m - n + 1);
		for (i = 2; i <= n; i++) {// 依次除以2、3、...、n
			s = 0; // 第一次除法前无余数
			for (j = k; j >= 1; j--) {// 从最高位第k位开始除
				s = a[j] + s * 10; // s为单项被除数
				b[j] = s / i; // b[j]存商
				s %= i;
			}
			while (b[k] == 0)
				// 去掉高位无意义的0
				k--;
			for (j = 1; j <= k; j++)
				a[j] = b[j];
		}
		return a;
	}

	/* 连乘方法,返回m*(m-1)*...*(n+1)*n的值 */
	private static void cumprod(int m, int n) throws Exception {
		if (m < n)// m必须>=n
			throw new Exception();
		k = 0;
		s = m;
		while (s != 0) {
			k++;
			a[k] = s % 10;
			s /= 10;
		}// 将m的各位数依次放入a中
		for (i = m - 1; i >= n; i--) {
			w = 0;
			for (j = 1; j <= k; j++) {
				a[j] = a[j] * i + w;// 乘数i与各位相乘,加进位值
				w = a[j] / 10;// 计算应进位的值
				a[j] %= 10;
			}
			while (w != 0) {
				k++;
				a[k] = w % 10;
				w /= 10;
			}// 分离最后进位数到数组高位
		}
	}
}


可以自己根据情况调整数组大小来获得更大数的阶乘、排列和组合

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值