当前位置:编程学习 > C/C++ >>

hdu 1042 N!(高精度乘法 + 缩进)

 题目大意:求n!, n 的上限是10000。

 


解题思路:高精度乘法 , 因为数据量比较大, 所以得用到缩进,但因为是乘法,缩进只能在10^5, 不然在乘的过程中就超过int型。然后数值位数大概在8000位以下。

 

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

const int MAXN = 100000;
const int N = 8000;

struct bign {
    int len;
    int s[N];
    
    bign() {
        this -> len = 1;
        memset(s, 0, sizeof(s));
    }
    bign (int number) {*this = number;}
    bign (const char* number) {*this = number;}
    
    bign change(bign cur) {
        bign now;
        now = cur;
        for (int i = 0; i < cur.len; i++)
            now.s[i] = cur.s[cur.len - i - 1];
        return now;
    }
    
    void delZore() {	// 删除前导0.
        bign now = change(*this);
        while (now.s[now.len - 1] == 0 && now.len > 1) {
            now.len--;
        }
        *this = change(now);
    }
    
    void put() {    // 输出数值。
        delZore();
        printf("%d", s[0]);
        for (int i = 1; i < len; i++)
            printf("%05d", s[i]);
    }
    
    bign operator = (const char *number) {
        memset(s, 0, sizeof(s));
        int dist = strlen(number);
        int k = dist % 8;
        for (int i = 0; i < k; i++)
            s[0] = s[0] * 10 + number[i] - '0';
	int cnt = 0;
	for (int i = k; i < dist; i++, cnt++)
	    s[cnt / 8 + 1] = s[cnt / 8 + 1] * 10 + number[i] - '0';
	len = cnt / 8 + 1;
	return *this;
    }

    bign operator = (int number) {
	char string[N];
	sprintf(string, "%d", number);
	*this = string;
	return *this;
    }

    bign operator * (const bign &cur){  
	bign sum, a, b;
	sum.len = 0; 
	a = a.change(*this);
	b = b.change(cur);

	for (int i = 0; i < a.len; i++){  
	    int g = 0;  

	    for (int j = 0; j < b.len; j++){  
		int x = a.s[i] * b.s[j] + g + sum.s[i + j];  
		sum.s[i + j] = x % MAXN;  
		g = x / MAXN;  
	    }  
	    sum.len = i + b.len;  

	    while (g){  
		sum.s[sum.len++] = g % MAXN;  
		g = g / MAXN;  
	    }  
	}  
	return sum.change(sum);  
    }  
};

int main() {
    int n;
    while (scanf("%d", &n) == 1) {
	bign sum = 1;
	for (int i = 2; i <= n; i++) {
	    bign now = i;
	    sum = sum * now;
	}       
	sum.put();
	printf("\n");
    }
    return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,