【发布时间】:2018-02-15 07:20:40
【问题描述】:
我有一个很长的阶乘程序,需要找到高达 100 的阶乘。它可以很好地找到 33 阶乘,但不能从 34 开始。有人可以帮助确定问题。
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
void bigFactorials(int n)
{
vector<int> v;//If I specify the size as v(1000) it works fine but I don't
//want to specify the size beforehand.
v.push_back(1);
// Complete this function
for(int i=2;i<=n;i++) {
int carry = 0, mul=0;
for(auto j=v.rbegin();j!=v.rend();j++) {
mul=i**j + carry;
carry=mul/10;
*j=mul%10;
}
if(carry)
v.insert(v.begin(),carry);
}
for(int i:v)
cout<<i;
}
int main()
{
int n;
cin >> n;
if( n>0 && n<101 )
bigFactorials(n);
return 0;
}
【问题讨论】:
-
@StoryTeller:我不认为他想存储 34!在
int。看起来他正在尝试使用向量将其存储在基本的 BigInt 实现中。 -
mul = i**j + carry;应该做什么? -
@Bob__ 取消引用迭代器 j 并乘以 i?
-
#include<bits/stdc++.h>不要这样做,这是一个内部头文件。它的唯一目的是包含using namespace std; -
将
unsigned long用于unsigned long carry = 0, mul=0;你会得到i**j + carry的溢出。如果你想达到 100,你需要 tong。
标签: c++ c++11 vector factorial