简体   繁体   中英

recursively add integers from 1^2 to n^2

i'm having some trouble recursively adding integers in java from 1^2 to n^2. I want to be able to recursively do this in the recurvMath method but all i'm getting is an infinite loop.

import java.util.Scanner;

public class Lab9Math {

int count = 0;
static double squareSum = 0;


public static void main(String[] args){

    int n = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter the value you want n to be: ");
    n = scan.nextInt();

    Lab9Math est = new Lab9Math();
    squareSum = est.recurvMath(n);
    System.out.println("Sum is: "+squareSum);
}

public int recurvMath(int n){

    System.out.println("N:" +n);
        if(n == 0){
            return 0; 
        }//end if
        if (n == 1){
            return 1;
        }//end if
        if (n > 1){
            return (recurvMath((int) ((int) n+Math.pow(n, 2))));
        }//end if
        return 0;
    }//end method       
}//end class

I'm not fully grasping the nature of defining this recursively, as i know that i can get to here:

return (int) (Math.pow(n, 2));

but i can't incorporate the calling of the recurvMath method correctly in order for it to work. Any help would be appreciated. Thanks!

In general, when trying to solve recursive problems, it helps to try to work them out in your head before programming them.

You want to sum all integers from 1 2 to n 2 . The first thing we need to do is express this in a way that lends itself to recursion. Well, another way of stating this sum is:

  • The sum of all integers from 1 2 to (n-1) 2 , plus n 2

That first step is usually the hardest because it's the most "obvious". For example, we know that "a + b + c" is the same as "a + b", plus "c", but we have to take a leap of faith of sorts and state it that way to get it into a recursive form.

So, now we have to take care of the special base case, 0:

  • When n is 0, the sum is 0.

So let's let recurvMath(n) be the sum of all integers from 1 2 to n 2 . Then, the above directly translates to:

  • recurvMath(n) = recurvMath(n-1) + n 2
  • recurvMath(0) = 0

And this is pretty easy to implement:

public int recurvMath(int n){    
    System.out.println("N:" +n);
    if(n == 0){
        return 0; 
    } else {
        return recurvMath(n-1) + (n * n);
    }
}

Note I've chosen to go with n * n instead of Math.pow() . This is because Math.pow() operates on double , not on int .

By the way, you may also want to protect yourself against a user entering negative numbers as input, which could get you stuck. You could use if (n <= 0) instead of if (n == 0) , or check for a negative input and throw eg IllegalArgumentException , or even use Math.abs() appropriately and give it the ability to work with negative numbers.


Also, for completeness, let's take a look at the problem in your original code. Your problem line is:

recurvMath((int) ((int) n+Math.pow(n, 2)))

Let's trace through this in our head. One of your int casts is unnecessary but ignoring that, when n == 3 this is recurvMath(3 + Math.pow(3, 2)) which is recurvMath(12) . Your number gets larger each time. You never hit your base cases of 1 or 0, and so you never terminate. Eventually you either get an integer overflow with incorrect results, or a stack overflow.

Try this

import java.util.Scanner;

public class Lab9Math {

int count = 0;
static double squareSum = 0;


public static void main(String[] args){

    int n = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter the value you want n to be: ");
    n = scan.nextInt();

    Lab9Math est = new Lab9Math();
    squareSum = est.recurvMath(n);
    System.out.println("Sum is: "+squareSum);
}

public int recurvMath(int n){

    System.out.println("N:" +n);
        if(n == 1){
            return 1; 
        }//end if
        // More simplified solution
        return recurvMath(n-1) + (int) Math.pow(n, 2); // Here is made changes

    }//end method       
}//end class

instead of saying:

return (recurvMath((int) ((int) n+Math.pow(n, 2))));

i instead said:

return (int) ((Math.pow(n, 2)+recurvMath(n-1)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM