大数运算

1. n! 

   当n比较大时,采用数组存放结果

#include <iostream>
using namespace std;
#define MAX 1000
//n比较小的时候
void n_(int n)
{
int result = 1;
for(int i = 2;i <= n; i ++)
result
*= i;

cout
<< result << endl;
}
//函数功能,求n!
void f(int n)
{
int a[MAX];
int p,h;//p 存储当前的结果的位数,h为进位
a[1] = 1; //用来存储运算结果
p = 1;
int j;
for(int i = 2;i <= n;i ++)//循环与2,3,4,5...n相乘
{
for(j = 1,h = 0;j <= p;j ++)
{
a[j]
= a[j] * i + h;
h
= a[j] / 10;
a[j]
= a[j] % 10;
}
while(h > 0)
{
a[j]
= h % 10;
h
/= 10;
j
++;
}
p
= j - 1;
}

for(int i = p;i >= 1; i --)
cout
<< a[i];
cout
<< endl;
}
int main()
{
int n = 50;
f(
50);

n_(
5);
return 0;
}

  2. 加法

 http://www.cnblogs.com/dolphin0520/archive/2011/04/11/2012867.html

加减乘除都有

#include <iostream>
#include
<stdio.h>
#include
<stdlib.h>
#include
<string.h>
using namespace std;

int max(int x,int y)
{
return x > y ? x : y;
}
int main()
{
char str1[510],str2[510];
int a[510] = {0},b[510] = {0},c[510];
int m,n,max_a_b = 0;
cin
>> str1;
cin
>> str2;
m
= strlen(str1),n = strlen(str2);
max_a_b
= max(m,n);
for(int i = 0;i < max_a_b; i ++)
{
a[m
-i-1] = str1[i]-48;
b[n
-i-1] = str2[i]-48;
}
for(int i = 0;i < max_a_b;i ++)
c[i]
= a[i] + b[i];
for(int i = 0;i < max_a_b;i ++)
{
c[i
+1] += c[i]/ 10;//加上进位
c[i] %= 10;
}
if(c[max_a_b] != 0)
for(int i = max_a_b;i >=0;i --)
cout
<< c[i];
else
for(int i = max_a_b-1;i >=0;i --)
cout
<< c[i];
cout
<< endl;
return 0;
}

  

原文地址:https://www.cnblogs.com/hitwtx/p/2153410.html