简体   繁体   English

递归地将1 ^ 2到n ^ 2的整数相加

[英]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. 我在将Java中的整数从1 ^ 2递归添加到n ^ 2时遇到了一些麻烦。 I want to be able to recursively do this in the recurvMath method but all i'm getting is an infinite loop. 我希望能够在recurvMath方法中以递归方式执行此操作,但我得到的只是一个无限循环。

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. 但是我无法正确合并recurvMath方法的调用才能使其正常工作。 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 . 您要对1 2到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 从1 2到(n-1) 2的所有整数的总和,再加上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. 例如,我们知道“ a + b + c”与“ a + b”加“ c”相同,但是我们必须进行种种信念飞跃,并以这种方式陈述以使其递归形成。

So, now we have to take care of the special base case, 0: 因此,现在我们要处理特殊的基本情况0:

  • When n is 0, the sum is 0. 当n为0时,总和为0。

So let's let recurvMath(n) be the sum of all integers from 1 2 to n 2 . 因此,让我们将recurvMath(n)设为从1 2到n 2的所有整数的和。 Then, the above directly translates to: 然后,以上内容直接转换为:

  • recurvMath(n) = recurvMath(n-1) + n 2 recurvMath(n)= recurvMath(n-1)+ n 2
  • recurvMath(0) = 0 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() . 注意,我选择使用n * n代替Math.pow() This is because Math.pow() operates on double , not on int . 这是因为Math.pow()double运算,而不对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. 您可以使用if (n <= 0)代替if (n == 0) ,或者检查是否为负数并抛出例如IllegalArgumentException ,甚至可以适当地使用Math.abs()并使其具有负数运算能力。


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) . 您的int强制转换之一是不必要的,但忽略了这一点,当n == 3这是recurvMath(3 + Math.pow(3, 2)) ,这是recurvMath(12) Your number gets larger each time. 每次您的人数都会增加。 You never hit your base cases of 1 or 0, and so you never terminate. 您永远不会遇到1或0的基本情况,因此永远也不会终止。 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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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