java阶乘计算

直接贴代码了

/**
  * 阶乘算法
  */

public String JieCheng(){
 /**
  * 阶乘算法一
  * @param args
  */
 static int jiectwo(int m){    //m>0
  //使用while循环语句计算1+1/2!+1/3!+1/20!之和
     int sum = 0,a = 1,i = 1;
     while(i < m){
        sum = sum+a;
        i = i+1;
        a = a*(i);
        //System.out.println(a+"===="+i);//a是i的阶乘结果
     }
    return sum+a;//sum是(m-1)阶乘之和  a是m的阶乘结果
 }
 static String jiecone(int n){//整数的阶乘   n>0
     int count = 0;
     String num="";
     factorial(n); //  3的阶乘3! num的阶乘 num!
     for(int i= a[0]; i>0; i--){
     count++;
     //System.out.print(/*"a[" + i + "]=" +*/ a[i]/* + " "*/);
     num+=a[i];
     }
  return "阶乘结果是"+count+"位数,"+n+"!="+ num;
 }
 /**
  * 阶乘算法二    此方法转http://blog.csdn.net/hengshan/archive/2005/11/13/528778.aspx
  *计算大数的阶乘,算法的主要思想就是将计算结果的每一位用数组的一位来表示:如要计算5!,那么首先将
  *(1) a[0]=1,然后a[0]=a[0]*2,a[0]=2,
  *(2) a[0]=a[0]*3,a[0]=6
  *(3) a[0]=a[0]*4,a[0]=24,此时a[1]=2,a[0]=4
  */
 static int a[] = new int [10000];
 static void factorial(int n) {
  for(int i=2; i< a.length; i++)  a[i] = 0; //将数组元素初始化
  a[0] = 1; //用数组的一项存放计算结果的位数
  a[1] = 1; //将第一项赋值为一
  for(int j= 2; j <= n; j++){
   int i=1;
   int c = 0; //c表示向高位的进位
   for(; i <= a[0]; i++){
    a[i] = a[i] * j + c;//将来自低位的计算结果和本位的结果相加
    c = a[i] / 10;
    a[i] = a[i] % 10;
   }
   for(; c != 0; i++){
    a[i] = c%10;
    c = c / 10;
   }
   a[0] = i - 1;
  }
 }
 /**
  * 阶乘算法三
  */
 static String jiecthr(int MAX){//MAX>1
  int i = 1;        
  long result=i;        
  long [] n = new long[MAX];        
  do {            
   result *= (i+1);                         
   n[i] = result;            
   i++;        
  } while (i<MAX) ;        
  n[0] = 1;//阶乘end
  return "阶乘结果"+MAX+"!="+result;
 }
 /**
  * 阶乘算法四
  */
 static String jiecthu(int MAX){ //任何自然数
  int i = 0;        
  long result=i;                 
  while (i<MAX){            
   result=fac(i+1);                             
   i++;        
  }  ;
  return "阶乘结果"+MAX+"!="+result;
 }
 static final int fac(int n) { //递归调用
  return (n==0)? 1 : n * fac(n - 1);
 }
 public static void main(String args[]){  
//  System.out.println(jiecone(1));
  System.out.println("阶乘求和="+jiectwo(5));//阶乘求和
//  System.out.println(jiecthr(2));
//  System.out.println(jiecthu(5));
 }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值