添加奇数的递归方法

时间:2014-04-16 10:00:10

标签: 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));
    }
}
}

我已将上述内容更改为以下内容。它输入数字后会编译停止。 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();

    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));
    }
}
}

4 个答案:

答案 0 :(得分:2)

import java.util。*; 公共阶级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

的奇数之和的答案

答案 1 :(得分:0)

public int addOdds(int n) {
  if (n <= 0) {
    return 0;
  }
  if (n % 2 == 0) {
    return addOdds(n - 1);  
  }
  return x + addOdds(n - 1);
}

小心,我从未测试过代码。

答案 2 :(得分:0)

class Oddsum {

public int addodd(int n)
 {
  if(n<=0)
  {
    return 0;    
  }
  if(n%2 != 0)
  {
    return (n+addodd(n-1));
  }
  else
  {
    return addodd(n-1);
  }
}

}

公共课Xyz {

 public static void main (String[] v)
 {
   int n = 9;
   Oddsum o = new Oddsum();
   int data =  o.addodd(n);
   System.out.print("sum:"+data);
 }

}

}

这很好用:):

答案 3 :(得分:0)

public static void main (String[] args){
        
       public static int oddSum(int s){
       if (s == 0)
           return 0;
       if (s < 0)
           return 0;
        else
            return s + oddSum(s -2);
       
         }
    }
相关问题