Hi,I have to have faster code (count Newton's binomial) , and I have not any idea how do this.
assumptions: use recursion, use only one function, 0<=K<=N<=33
int newton(int N, int K)
{
if (N == K || K == 0) return 1;
else if(K<N && N<=33) return newton(N-1, K-1) + newton(N-1, K);
}
Sure, that works too, but there is an old expression about polishing a poo that comes to mind. Making bad code faster is pointless. I can fine tune bubble sort all day and never get any speed out of it.
#include <iostream>
#include <vector>
usingnamespace std;
using INT = unsignedlonglong;
int main()
{
constint NMAX = 33;
vector< vector<INT> > nCr;
for ( int n = 0; n <= NMAX; n++ )
{
vector<INT> row( 1 + n );
for ( int r = 0; r <= n; r++ ) row[r] = ( r == 0 || r == n ? 1 : nCr[n-1][r-1] + nCr[n-1][r] );
nCr.push_back( row );
}
for ( int n = 1; n <= NMAX; n++ )
{
cout << n << "Cr = ";
for ( int r = 0; r <= n; r++ ) cout << nCr[n][r] << ' ';
cout << '\n';
}
}
Run the 'too slow' algorithm one time and dump the answers to code.
preferably, using the 'memory' of what you already did concept to make that less painful if you run it out for a very large number? The above runs in the online compiler PDQ, but if you want it even faster, you can just spew the output from a pre-built table.
The run once thing only works for tractable problems, of course. And, honestly, for this one, you probably could have looked up the hard-coded answers online.
Chances are this is a "basic algorithms" homework.
If I were a betting man, I'd say chances are this is a "code competition" question. Not that it makes the question any less valid (well, sometimes).
Notice the tell-tale sign of bounds given in the prompt 0<=K<=N<=33, that the competitor mistakenly thinks they need to put as if-conditions in the actual code.
That makes me even more glad I saved the link, so I could share it. :)
I "like" how the OP dropped his "do all the work for me for free" turd and hasn't bothered to reply back. Even after some people offered legitimate help.