假设一个数a1a2a3...an是一个n位数,那么数a1a2a3...an*b的位数和为(a1*b+a2*b+a3*b+...+an*b)=(a1+a2+a3+...+an)*b这也就是说,每次已计算出来的积乘以一个数,等于积乘以该数的位数和,这样就将阶乘再求和变成边乘边求和。
package com.wy.test;
public class Factorial3 {
private int n;
public Factorial3(int n) {
this.n=n;
}
public int factorial(){
long sum=1;
if(n>1){
//循环求阶乘
while(n>1){
sum*=n;
//求每步阶乘结果的位数和
sum = getSum(sum);
n--;
}
}else if(n==1||n==0)return 1;
else return -1;
return getSum(sum);
}
private int getSum(long sum){
if(sum>=10){
int s=0;
//循环取数字的每一位
while(true){
s+=sum%10;
sum/=10;
if(sum==0) break;
}
return getSum(s);
}else
return (int) sum;
}
public static void main(String[] args) {
Factorial3 sof = new Factorial3(23);
System.out.println(sof.factorial());
}
} |