• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

strange function problem

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

Zantal

Member
Joined
Mar 19, 2009
Ok so a friend of mine got stuck with some homework, and then i got stuck too trying to help him

the problem is the following.

Implement a function "sum" in c++ defined like this

Sum(0,y) = y for all positive Y
Sum(x,y) = Sum(x-1,1) + Sum(x-1,2) + Sum(x-1,3) + . . . + Sum(x-1,y) for all positive Ys and Xs

here are some of the possible results;

Sum(1,3) = 6
Sum(2,3) = 10
Sum(4,10) = 2002

I am utterly lost as I am really not getting it, can someone shed some light on it please?
 
Hey there, I just wrote the function in C++ and got your expected results so I'll give you my small piece of code used.

Code:
#include <iostream>

// STD Namespace
using namespace std;

// Function
int sum(int x, int y);

// Main
int main() {

	cout << sum(1,3) << endl
		<< sum(2,3) << endl
		 << sum(4,10) << endl;
	
	return 0;

}

// Definition
int sum(int x, int y) {

	int total = 0;

	if (x==0) {

		return y;

	}

	else {

		for (int i=1;i<=y;i++) {

			total += sum(x-1,i);
		}
	}

	return total;

}
 
You are a genius!

Got there before me for sure, may be that I was a little bit tired after work and couldn't think straight :p

thank you very much =)
 
Back