【问题标题】:c++ sum large numbers, Program stops?c ++求和大数,程序停止?
【发布时间】:2017-02-17 06:54:59
【问题描述】:

我正在运行这两个函数,它们执行相同的计算“对前 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) ....
  }
}

【问题讨论】:

  • 您是否收到错误消息?还是该程序的运行时间很长?顺便说一句:你应该在这个问题中添加 c++ 标签
  • 编译器没有错误,运行时间太长了,所以windows一到recusiveSum方法就会停止程序运行? euhh 我不知道如何添加 c++ 标签,对不起:D
  • 没问题,我现在添加了(但您必须接受编辑)。

标签: c++ recursion sum runtime iteration


【解决方案1】:

您可能需要一个arbitrary precision arithmetic 库,例如GMPlib,以避免arithmetic overflows。你应该害怕stack overflow

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

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多