您的位置:首页 > 其它

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

2011-11-12 20:07 337 查看
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;
}// 分离最后进位数到数组高位
}
}
}


可以自己根据情况调整数组大小来获得更大数的阶乘、排列和组合
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  exception string class