2013年3月15日 星期五

How to sum the Integers from 1 to N.

Question:
How to sum the Integers from 1 to N.

Answer:
#include "stdafx.h"
#include 

using namespace std;

int allPlus(int n);

int _tmain(int argc, _TCHAR* argv[])
{
    const int n = 100;
    int sum = allPlus(n);

    cout << sum << endl;

    std::cin.get();
 return 0;
}

int allPlus(int n)
{
    if (n == 0)
        return 0;

    return n + allPlus(n-1);
}


Advanced Answer:
Change function allPlus below for O(1) time complexity
int allPlus(int n)
{
    return (1 + n) * n / 2;
}


* All answer just my answer, I am no sure if it is correct.

沒有留言:

張貼留言