Click to See Complete Forum and Search --> : Need help how to start


vietdo
October 22nd, 2005, 05:17 PM
Write both an iterative and recursive algorithm for solving the following problem: The input consists of two positive integers, n and k. Compute and return the total number of ways n can be written as a sum of k positive integers. Here the order of the integers matter, so that 1 + 3 is different than 3 + 1. So for n=4 and k = 2, your program should return 3, since there are three ways of adding two positive integers to get 4: 1+3, 2+2, and 3+1

mehdi62b
October 22nd, 2005, 06:05 PM
So for n=4 and k = 2, your program should return 3

*|* * * (1+3)
* *|* * (2+2)

* * *|* (3+1)

so the answer is

c(n-1,k-1)

fardream
October 25th, 2005, 09:31 PM
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

ofstream fileOut;

void getFunc(string headStr, int n, int k)
{
if(k==1)
{
fileOut<<headStr<<n<<"\n";
return;
}
string temHead;
char numStr[20];

for(int i=1; i<n; i++)
{
sprintf(numStr,"%d+",i);
temHead=headStr+numStr;
getFunc(temHead, n-i,k-1);
}

}

void main()
{
fileOut.open("allExpression.txt");
if(fileOut.fail())
return;

getFunc("", 4,2);

}