1 /***************************************************************************************************/ 2 /* Copyright (C) 2008 Chipset 3 /* 4 /* This program is free software: you can redistribute it and/or modify 5 /* it under the terms of the GNU Affero General Public License as 6 /* published by the Free Software Foundation, either version 3 of the 7 /* License, or (at your option) any later version. 8 /* 9 /* but WITHOUT ANY WARRANTY; without even the implied warranty of 10 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 /* GNU Affero General Public License for more details. 12 /* 13 /* You should have received a copy of the GNU Affero General Public License 14 /* along with this program. If not, see <http://www.gnu.org/licenses/>. 15 /****************************************************************************************************/ 16 17 #include <iostream> 18 #include <vector> 19 void cal_factorial(std::vector<int>& a, int n) 20 { 21 int carry = 0; 22 a.push_back(1); 23 int tmp; 24 25 for(int i = 2; i <= n; ++i) 26 { 27 for(int j = 0; j < a.size(); ++j) 28 { 29 tmp = a[j] * i + carry; 30 a[j] = tmp % 10; 31 carry = tmp / 10; 32 } 33 while(carry) 34 { 35 a.push_back(carry % 10); 36 carry /= 10; 37 } 38 } 39 } 40 41 void show_factorial(const std::vector<int>& v, int n) 42 { 43 for(int i = v.size() - 1; i > -1; --i) 44 std::cout << v[i]; 45 } 46 47 //测试 48 #include <windows.h> 49 int main() 50 { 51 int n; 52 do{ 53 std::cout << "Input a number(greater than 0) for factorial:\n"; 54 std::cin >> n; 55 if(n < 0) 56 std::cout << "Must be greater than 0\n"; 57 }while(n < 0); 58 Sleep(1000); 59 std::vector<int> v; 60 DWORD time = GetTickCount(); 61 cal_factorial(v, n); 62 time = GetTickCount() - time; 63 std::cout << n << "! is as long as " << v.size() << " bit(s). " << n << "! ==\n" ; 64 show_factorial(v, n); 65 std::cout << "\ncalculating " << n << "! used " << time << " ms, memory used: " 66 << v.size()* sizeof(int) << " bytes.\n"; 67 system("pause"); 68 return 0; 69 } 以上算法速度比较慢,仅仅供初学者参考,更快的版本在这里http://www.cppblog.com/Files/Chipset/Factorial.zip
|
|
| 日 | 一 | 二 | 三 | 四 | 五 | 六 |
---|
28 | 29 | 30 | 31 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|
常用链接
留言簿(2)
随笔分类(99)
收藏夹(2)
主页
最新评论
|
|