package com.lpc.algorithm;
/**
* 利用数组解决N!问题
* @author hadoop
*
*/
public class Factorial {
//要计算的阶乘数,默认为0
private int n=0;
//定义要使用的数组(把计算的数的每一位对应到数组)如57848 对应为a[0]=8 a[1]=4 a[2]=8 a[3]=7 a[4]=5
private int[] a = new int[5000000];
//计算结果的位数,默认从1开始,因为0!=1 1!=1
int w = 1;
/**
* 利用数组进行计算
* @param n 要计算的阶乘数
*/
public void Calc(int n){
this.n=n;
this.w=1;
//进位 默认为0
int c = 0;
//0!=1
a[0]=1;
//按照中间结果和下一个要乘的数相乘,用乘数和中间结果的每一位去乘,然后对每一位作进位处理
for(int i = 1; i <= n; i++){
//将进位清零
c=0;
//遍历中间结果的每一位
for(int j=0; j<this.w;j++){
//t:中间结果
int t = a[j]*i+c;
//当前位存储的是中间结果的余数
a[j]= t%10;
//进位
c = t/10;
}
//最高位可能产生进位,对其进行处理
while(c > 0){
//最高位增加(可能会产生越界的问题)
w++;
a[w-1] = c % 10;
//进位
c = c / 10;
}
}
}
public void Print(){
System.out.println("N: "+ this.n);
System.out.println("位数 : " + this.w);
StringBuilder sb = new StringBuilder();
for(int i = this.w ; i > 0 ; i--){
sb.append(this.a[i-1]);
}
System.out.println("结果 : " + sb.toString());
}
public void Clear() {
for (int i = this.w; i > 0; i--) {
this.a[i - 1] = 0;
}
}
public static void main(String[] args) {
Factorial f = new Factorial();
f.Calc(3);
f.Print();
f.Clear();
* 利用数组解决N!问题
* @author hadoop
*
*/
public class Factorial {
//要计算的阶乘数,默认为0
private int n=0;
//定义要使用的数组(把计算的数的每一位对应到数组)如57848 对应为a[0]=8 a[1]=4 a[2]=8 a[3]=7 a[4]=5
private int[] a = new int[5000000];
//计算结果的位数,默认从1开始,因为0!=1 1!=1
int w = 1;
/**
* 利用数组进行计算
* @param n 要计算的阶乘数
*/
public void Calc(int n){
this.n=n;
this.w=1;
//进位 默认为0
int c = 0;
//0!=1
a[0]=1;
//按照中间结果和下一个要乘的数相乘,用乘数和中间结果的每一位去乘,然后对每一位作进位处理
for(int i = 1; i <= n; i++){
//将进位清零
c=0;
//遍历中间结果的每一位
for(int j=0; j<this.w;j++){
//t:中间结果
int t = a[j]*i+c;
//当前位存储的是中间结果的余数
a[j]= t%10;
//进位
c = t/10;
}
//最高位可能产生进位,对其进行处理
while(c > 0){
//最高位增加(可能会产生越界的问题)
w++;
a[w-1] = c % 10;
//进位
c = c / 10;
}
}
}
public void Print(){
System.out.println("N: "+ this.n);
System.out.println("位数 : " + this.w);
StringBuilder sb = new StringBuilder();
for(int i = this.w ; i > 0 ; i--){
sb.append(this.a[i-1]);
}
System.out.println("结果 : " + sb.toString());
}
public void Clear() {
for (int i = this.w; i > 0; i--) {
this.a[i - 1] = 0;
}
}
public static void main(String[] args) {
Factorial f = new Factorial();
f.Calc(3);
f.Print();
f.Clear();
f.Calc(10);
f.Print();
f.Clear();
f.Print();
f.Clear();
f.Calc(100);
f.Print();
f.Clear();
}
}
f.Print();
f.Clear();
}
}