码迷,mamicode.com
首页 > 其他好文 > 详细

蓝桥杯 BASIC 30 阶乘计算(大数)

时间:2015-03-16 23:11:46      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:蓝桥杯   acm   

【思路】:大数基本都是这思路,采用数组或者字符串,每个数采用倒序的方式从头开始存储。每次进位进到下一位上。

【AC代码】:两个数组来回颠倒。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iomanip>
using namespace std;

#define MAX 3000

int cal(int *s, int len, int n, int *d)
{
	int i = 0, temp = 0;
	for (i = 0; i < len; i++)
	{
		temp = s[i] * n + temp;
		d[i] = temp%10;
		temp = temp/10;
	}
	while (temp)
	{
		d[i++] = temp%10;
		temp = temp/10;
	}
	return i;
}

void output(int *s, int len)
{
	int i = 0;
	while (len)
	{
		cout << s[--len];
	}
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int n =0, i = 0, j = 1, k = 0;
	int s1[MAX]={1}, s2[MAX];
	cin >> n;
	for (i = 1; i <= n; i++)
	{
		if (j > 0)
		{
			k = cal(s1, j, i, s2);
			j = 0;
		}
		else
		{
			j = cal(s2, k, i, s1);
			k = 0;
		}
	}
	if (0 == n%2)
		output(s1, j);
	else
		output(s2, k);
}

【AC代码2】:一个数组。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iomanip>
using namespace std;

#define MAX 3000

int cal(int *s, int len, int n)
{
	int i = 0, temp = 0;
	for (i = 0; i < len; i++)
	{
		temp = s[i] * n + temp;
		s[i] = temp%10;
		temp = temp/10;
	}
	while (temp)
	{
		s[i++] = temp%10;
		temp = temp/10;
	}
	return i;
}

void output(int *s, int len)
{
	int i = 0;
	while (len)
	{
		cout << s[--len];
	}
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int n =0, i = 0, len = 1;
	int s1[MAX]={1};
	cin >> n;
	for (i = 1; i <= n; i++)
	{
		len = cal(s1, len, i);
	}
	output(s1, len);
}


蓝桥杯 BASIC 30 阶乘计算(大数)

标签:蓝桥杯   acm   

原文地址:http://blog.csdn.net/weijj6608/article/details/44315815

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!