gpt4 book ai didi

c++求大数,程序停止了吗?

转载 作者:行者123 更新时间:2023-11-28 05:17:37 25 4
gpt4 key购买 nike

我正在运行这两个函数,它们执行相同的计算“对前 N 个整数求和”,然后比较每个函数的运行时间。该程序在输入较小的情况下工作正常,但问题是当我输入像 1000000 这样的大数字时,它会计算第一个方法“iterativeSum()”,然后一旦到达 recursiveSum() 它就会停止工作。

我不确定,但您认为这可能是因为 cout 造成的吗?

#include <stdio.h>
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

void iterativeSum(int);
int RecursiveSum(int);


int main()
{
long long posInt;
std::cout << "Enter a positive integer: ";
std::cin >> posInt;

int start_s=clock();
iterativeSum(posInt);
int stop_s=clock();

int start_s1=clock();
cout << "\nThe recursive algorithm to sum the first N integers of "<< posInt << " is: "<< RecursiveSum(posInt) << endl;
int stop_s1=clock();

cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)/1000 << endl;

cout << "time: " << (stop_s1-start_s1)/double(CLOCKS_PER_SEC)/1000 << endl;


return 0;
}

void iterativeSum(int posInt)
{
//positive Integer >=0
int sum = 0;


//loop through and get only postive integers and sum them up.
// postcondion met at i = 0

for(int i = 0; i <= posInt;i++)
{
sum +=i;
}
//output the positive integers to the screen
std::cout <<"\nThe iterative algorithm to sum the first N integers of " <<posInt <<" is: " << sum << "\n";
}


int RecursiveSum(int n)
{
if(n == 1) // base case
{
return 1;
}
else
{
return n + RecursiveSum(n - 1); //This is n + (n - 1) + (n - 2) ....
}
}

最佳答案

您可能需要一个 arbitrary precision arithmetic类似图书馆 GMPlib , 避免 arithmetic overflows .你应该害怕stack overflow .

call stack通常是有限的(例如一兆字节)。参见 this

关于c++求大数,程序停止了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42291285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com