计算4的1万次方的结果

基本的思想就是模拟人手算的方法,来完成大数运算,很简单

using System;
using System.Collections;
using System.Diagnostics;

namespace IBMS.Algorithem
{
 /// <summary>
 /// N2Class
 /// </summary>
 class N2
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   N2 newObject = new N2();

   int baseNum = 4;
   int testN = 10000;

   Console.WriteLine("Std Math Lib Caculating result:"+Math.Pow(baseNum,testN).ToString());
   Console.WriteLine("Wait...now begin to caculate..");

   int[] result = newObject.Power( baseNum,testN );
   
   Console.WriteLine("Caculate Result:");

   for(int i=result.Length-1; i>=0; i--)
   {
    Console.Write(result[i]);
   }

   Console.WriteLine("");
  }

  int[] Power(int baseNum, int n)
  {
   
   int [] result;

   if(n<0)
   {
    
    throw new Exception("现在还不支持负指数");
   }
   if(n==0)
   {
    result= new int[1];
    result[0]=1;
    return result;
   }

   //获得结果位数
   int size = (int)(n*Math.Log10(baseNum))+1;
  
   result = new int[size];
   result[0]=1;

   for(int i=0; i< n; i++)
   {
    Multi_Vector(result,baseNum);
    //Console.WriteLine("Caculate {0}'s {1} ",baseNum,i+1);
   }
   
   return result;
  }

  void CheckCarray(int []m,int index)
  {
   
   if(m[index]>=10)
   {
    //向高位进位,模拟手算
    m[index+1]+=m[index]/10;
    
    //设置当前位
    m[index] %= 10;

    //检查下一个位时候需要进位
    CheckCarray(m,index+1);
   }
  }

  
  /// <summary>
  /// 矢量和一个整数的乘法运算
  /// </summary>
  /// <param name="m">矢量</param>
  /// <param name="n">乘数</param>
  void Multi_Vector(int [] m, int n)
  {
   int totalBit=0;

   for(int i=m.Length-1;i>=0; i--)
   {
    if(m[i]>0)
    {
     totalBit = i+1; //获得最高位
     break;
    }
   }
   
   Debug.Assert(totalBit!=0);

   for(int  i=totalBit-1; i>=0; i--)
   {
    //从高位到低位开始算
    int temp = m[i]*n;
    //产生一个进位
    if(temp>=10)
    { 
     //向高位进位,模拟手算
     m[i+1]+=temp/10;
     //检查该位是否还需要进位
     CheckCarray(m,i+1);
     temp %= 10;
    }
    m[i]= temp;
   }
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值