java - 奇数相加的递归方法

标签 java recursion numbers sum

我有下面的代码片段,用于使用递归方法来添加奇数之和。 我已经成功地编写了迭代方法,该方法将用户输入的 n 和 m 之间的所有奇数相加。我想实现这个目标,但开始得很慢,以确保我了解正在发生的事情。 我知道迭代执行更有意义,但是我正在尝试这两种类型,看看哪种更有效。我被困在下面,因为它没有做我想要的事情,我不明白为什么。

import java.util.*;

public class SumofOdd
{
    public static void main (String [] args)
    {
    int n = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter an odd number");
    n = sc.nextInt();
    int x = add(n);
}

public static int add(int x)
{
    if (x == 0)
    {
        return 0;
    }
    else
    {
        return (x + add(x-1));
    }
}
}

我已将上面更改为以下。但它会编译,但在我输入数字后停止。 导入java.util.*;

public class SumofOdd
{
    public static void main (String [] args)
    {
    int n = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter an odd number");
    n = sc.nextInt();

    if (n%2 == 0)
    {
        System.out.println("The number entered is even");
    }
    else
    {
        int x = add(n);
    }
}

public static int add(int x)
{
    if (x <= 0)
    {
        return 0;
    }
    else
    {
        return (x + add(x-2));
    }
}
}

最佳答案

import java.util.*;
public class OddR{

    public static void main (String Args [])
    {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter an odd number");
        int max = s.nextInt();
        if((max% 2) == 0) {
            System.out.println(max + " is Even number and therefore is invalid");
        }
        else{
            System.out.println("Enter a greater odd number");
            int m = s.nextInt();
            if (m <max){
                System.out.println("Invalid data");

            }
            else{
                if((m % 2) == 0) {
                    System.out.println(m + " is Even number and therefore is invalid");

                }
                else{

                    int data =  (addodd(m)- addodd(max))+max;
                    System.out.print("sum:"+data);
                }
            }
        }
    }

    public static int addodd(int m)
    {

        if(m<=0)
        {
            return 0;    
        }

        if(m%2 != 0)
        {
            return (m+addodd(m-1));
        }
        else
        {
            return addodd(m-1);
        }
    }
}

这是从n到m的奇数之和的递归答案

关于java - 奇数相加的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23106077/

相关文章:

Java - 如何阻止用户输入整数以外的内容?

java - 数独的逻辑求解算法(Java)

c - 在 C 中手动从递归获取输出

C练习任务(递归)

javascript - 如何动态更改输入数字的值并验证其中的数据?

python - 如何在python中将字符串转换为数字

java - 错误 : More than one file was found with OS independent path 'META-INF/DEPENDENCIES'

java - Java中Knapsack的递归解法

java - 星号代表带有单独测试仪的数字

C 计算一个数组中的 int 在另一个数组中出现的频率