2017-02-17 3 views
0

これらの2つの関数を実行して、同じ計算を「最初のN個の整数の合計」とし、それぞれの実行時間を比較しています。プログラムは小さな入力で正常に動作しますが、問題は1000000のような大きな数値を入力すると最初のメソッド "iterativeSum()"が計算され、recursiveSum()に到達するとすぐに機能が停止します。C++の大きな数値を合計すると、プログラムは停止しますか?

確かに分かりませんが、これは詐欺のためかもしれないと思いますか?

#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) .... 
    } 
} 
+0

エラーメッセージが表示されますか?それとも、プログラムの実行時間が本当に長いですか? BTW:この質問にC++タグを追加する必要があります – Aemyl

+0

コンパイラのエラーはありません。実行時間が長すぎるため、ウィンドウはrecusiveSumメソッドに到達するとすぐにプログラムの実行を停止しますか?あなたはC++タグを追加する方法はわかりません。申し訳ありません:D – Ivawen

+0

問題はありません。今すぐ追加しましたが、編集を受け入れる必要があります。 – Aemyl

答えて

関連する問題