C++中数字很大的函数
Functions with very big numbers in C++
我对C++还很陌生,一直在尝试编写一个程序来处理非常大的输入数字(7e+11ish)。它适用于小数字,但不适用于这些大数字。我意识到这是因为非常大的数字不适合int,但当我尝试其他类型,如__int64、long-long-int、unsigned long-longint和uint64_t时,函数"nextsmallstactor"不起作用(它通常输出0,因此在除以输出a时会触发错误)。那我该用什么?这个代码应该取一个大的数字,重复地用每次除以它的最小数字除以它,并在最后输出最高素数a。
#include <iostream>
using namespace std;
int numberToFactorise = 700000000000;
int nextsmallestfactor(int numbertofactorise){
for (int factor = 2; factor < numbertofactorise; factor++){
if (numbertofactorise%factor == 0){
return factor;
}
}
}
int main(){
int quotient = numberToFactorise;
int a=1;
while (quotient > 1){
a = nextsmallestfactor(quotient);
quotient = quotient / a;
};
cout << a;
cout << endl;
system("PAUSE");
return 0;
}
非常感谢您的帮助。
问题是,如果给函数一个素数,那么代码实际上永远不会返回值,因此会产生未定义的行为。当我们输入素数时,让我们写出循环的迭代:
nextsmallestfactor( 5 ):
factor | numbertofactorise % factor
----------------------------
2 | 5%2 = 1
3 | 5%3 = 2
4 | 5%4 = 1
END (no return)
如果您将条件更改为检查系数并包括numbertofactorize
,则会执行以下操作:
nextsmallestfactor( 5 ):
factor | numbertofactorise % factor
----------------------------
2 | 5%2 = 1
3 | 5%3 = 2
4 | 5%4 = 1
5 | 5%5 = 0 ---> return 5;
如果你想编写一些能够处理巨大数字(及其所有数字)的C++代码,你需要bignum。然后我建议您使用一些现有的bignum库,如GMPLIB;你将能够计算例如1000的阶乘及其所有数字。
不要试图重塑你自己的bignum库;因为复杂的底层算法(比天真的算法更有效)很难理解(也很难重新发明)。
一些语言和实现(例如Common Lisp的SBCL)具有内置bignum。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 函数在许多数字上转换为基数 1 时减去 2?
- 函数如何使用引用返回所需的数字?
- 当我尝试在 Main 中调用插入函数时,它不是取数字?
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- 如何在 setup() 函数中使用数字引脚转动电机?
- C++ python 中的函数返回数字而不是字符串
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 将 C 函数转换为 C++ 以检查数字是否有效
- 在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 在 c++ 中将数字转换为矢量数组的函数
- 使用带有一个参数函数的递归找到数字的平方
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 为什么当我在 c++ 中运行函数时,我的代码显示数字 53
- 我有模板功能.通过使用函数std::for_each,用这个容器中的最大数字替换每个正数
- 如何用不同的参数类型和数字回调函数
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 素数检查 C++ 函数输出非素数的数字
- C++构造函数:数字常量之前的预期标识符