开发者

Recurrsion for sum of the first k series 1 + (1/2)-(1/3)+(1/4)......(1/k)

开发者 https://www.devze.com 2023-04-12 18:13 出处:网络
I am trying to write a recurssive method that excepts an integer argument k and returns as a double the sum of the first k terms of the series such as: 1 + (1/2)-(1/3)+(1/4)......(1/k). i have written

I am trying to write a recurssive method that excepts an integer argument k and returns as a double the sum of the first k terms of the series such as: 1 + (1/2)-(1/3)+(1/4)......(1/k). i have written several recursive methods but this one stumps me. Is my method set up properly? My main problem is I don't what variables i should create in the **sumHelper method and how to manipulate them. Please help! It will be greatly

public static double sum (int k){
    if(k == 0) return 0;
    if(k == 1) return 1 + (1.0/2);      

    double total = 1 + sumHelper(k);
    return total; 

开发者_StackOverflow社区}

public static double sumHelper(int k) {
    if (k == 2) return 1.0/k;


    return ; ????


Perhaps something along these lines

public static double sum(int k) {
    if (k <= 0) return 0;
    if (k == 1) return 1;
    if (k % 2 == 0)
        return 1.0/k + sum(k-1);
    else
        return -1.0/k + sum(k-1);
}


you don't really need a helper

use the value of k to see whether it's a + or a -

if even it's a +, if odd then it's -

exception is k==1 (since it's odd and we are adding

public static double sum(int k){
    if (k<=1) return (double) k;
    return ((k%2==0)? 1 : -1)*(1/(double)k) + sum(k-1);
}

for k=4:

sum(4) -> 1/4 + sum(3)
sum(3) -> -1/3 + sum(2)
sum(2) -> 1/2 + sum(1)
sum(1) = 1

==>
sum(4) = 1 + 1/2 - 1/3 + 1/4


return (sumHelper(k-1)+Math.pow(-1.0, (double)k)*1/k);


You're overcomplicating it:

public double sum(int k)
{
    if(k==1)
       return 1;
    return (k%2==0>1:-1)*1.0/k + sum(k-1);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消