# Need some advice with a recursive problem

I having a hard time trying to create an recursive funtion that will determine the fp value of 1/1 + 1/2 - 1/3 + 1/4 - 1/5....for any number of n (1/n). Any pointers will be greatly appreciated.

Thanks,

O

• [grey]I having a hard time trying to create an recursive funtion that will determine the fp value of 1/1 + 1/2 - 1/3 + 1/4 - 1/5....for any number of n (1/n). Any pointers will be greatly appreciated.
[/grey]

[green]
Hi!
The following code should be all you need. Do me a favour and inform the community next time about your language of choice. If you need the program in Delphi or Perl or any other language, just mail me and I'll see what I can do.

HTH
[/green]

[code][size=2]
#include
using namespace std;

double calc1_x (int n);

int
main (void)
{
int n;

cout << "n: ";
cin >> n;

cout << "Result = " << calc1_x (n) << endl;

return 0;
}

double
calc1_x (int n)
{
if (n == 1)
return 1;

return 1.0/n + calc1_x (n - 1);
}
[/size][/code]
• friend iam writing the function ; read it once

int sum(int beg,float n)
{
if(n==0)
return -1;
if(beg>n)
return 0;
else
return (1/float(beg)+pow(-1,beg+1)*sum(beg++,n));
}
this is c styled function which takes 2 parameters
beg should be initialzed to 1 and n>= beg
for example u want to calculate ur problem for n=10
call it as sum(1,10)
it will return u the required answer if any bug do
thanx

: I having a hard time trying to create an recursive funtion that will determine the fp value of 1/1 + 1/2 - 1/3 + 1/4 - 1/5....for any number of n (1/n). Any pointers will be greatly appreciated.
:
: Thanks,
:
: O
:

• [b][red]This message was edited by gaetano at 2004-5-11 2:46:35[/red][/b][hr]
[green]
Hi!
After a few corrections this algorithm works at least, but some questions just won't be answered in my considerations. So please help me:
- What advantages offers this algorithm which my don't?
- Why do you take an float as the second parameter? It's obviously unnecessary as you're always checking against an integer ...

And some other Comments I'd like to do:
- What about calculating the n-th power of 1? It's always 1! At last the whole term with the power is useless, because the 1 should be positive and _not_ negative.
- All these unnecessary calculations have no effect and prolong the calculation time!
[/green]

[code][size=2]
double
sum(int beg,float n)
{
if(n==0)
return -1;
if(beg>n)
return 0;
else
return (1/(double) beg + pow (1, beg+1) * sum (++beg, n));
}
[/size][/code]

[red]My code:[/red]
[code][size=2]
double
calc1_x (int n)
{
if (n == 1)
return 1;

return 1.0/n + calc1_x (n - 1);
}
[/size][/code]