Can you tell me how to calculate
f(n)=f(n-1)+n^5
f(0)=1
without using recursive
Thank you
Printable View
Can you tell me how to calculate
f(n)=f(n-1)+n^5
f(0)=1
without using recursive
Thank you
In a for() loop?Quote:
Originally Posted by Kawaguchi
But how :(?
Maybe like this:
- petterCode:int func(int n)
{
int res = 1;
while (n > 0)
{
res += n*n*n*n*n;
n--;
}
return res;
}
As VladimirF said. A for loop. Complete untested ..
You could even modify code to do things inplace..Code:template< typename T >
std::vector < T >
sum_of_series ( std::vector < T >& in )
{
std::vector < T > out;
typedef std::vector < T >::size_type size_type;
size_type const sz = in.size ();
if ( ! sz )
// throw (); // do something ..
out.resize ( sz );
out [ 0 ] = 1;
for ( size_type n( 1 ); n< sz; ++n)
{
out [ n ] = in [ n - 1 ] + ::pow ( n, 5 ) ;
}
return ( out );
}
...or build a lookup table for performance.
Code:int series[] = {1, 2, 34, 277 /* more data here */};
result = series[2]; // Result of f(2).
thanks everyone, you know so much :)
Also possible to calculate the series in one go:
Hope this helpsCode:int f(int i)
{
return
static_cast<int>(
+ 2 * std::pow(
i + 1,
6)
- 6 * std::pow(
i + 1,
5)
+ 5 * std::pow(
i + 1,
4)
- 1 * std::pow(
i + 1,
2)
) / 12 + 1;
}
Just for the fun. You can use recursion in Meta-template programming to let the compiler generate the value for you as long as recursion in compile-time is okay as compare to recursion in run-time. :)
Code:#include <iostream>
using namespace std;
template<int n>
class Series
{
public:
static int get()
{
return Series<n-1>::value() + n*n*n*n*n;
}
};
template<>
class Series<0>
{
public:
static int value()
{
return 1;
}
};
int main()
{
cout << Series<3>::value(); // f(3)
}