【问题标题】:Nth output sum of (N-2)th and (N-1)th第 (N-2)th 和 (N-1)th 的第 N 个输出总和
【发布时间】:2016-11-30 04:44:24
【问题描述】:

无论我尝试什么,我都无法弄清楚这个问题,我可能只是想多了,我能得到一点帮助吗?我已经尝试了各种不同的 for 循环,但我不知道如何获取这些值

for(int a = 1; a<1000; a++) 

我想让它显示为 a+b 但我不认为这是可能的

以下代码以斐波那契而闻名,其中第 N 个输出是 (N- 2)th 和 (N-1)th 值。编写 for 表达式来完成相同的任务。

int a=1, b=1; 
while (a < 10000 ){ 
 System.out.print(a+" "+b+" "); 
 b+=a+=b; 
} 

【问题讨论】:

  • 问题是什么?

标签: java for-loop while-loop


【解决方案1】:

将while循环转换为for循环,就是:

for (int a=1, int b=1; a < 10000; b+=a+=b ){ 
   System.out.print(a+" "+b+" "); 
} 

【讨论】:

  • 我花了很多答案才找到正确的答案:)。
【解决方案2】:

你可以使用递归来做到这一点:

public int fibonacci(int n)  {
    if(n == 0) {
        return 0;
    } else if(n == 1) {
        return 1;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

【讨论】:

  • 唯一的事情是我应该用 for 循环来做这件事,这是我想不通的
  • 呃,那会很慢。递归并不总是解决问题的最佳方法;-)
【解决方案3】:

如果要使用循环,可以执行以下操作(借用this 答案):

public int fibonacci(int n)  {
    if (n == 0)
        return 1;
    if (n == 1)
        return 3;
    int grandparent = 1;
    int parent = 3;
    int curr = 0;
    for(int i=2; i <= n; i++){
        curr = 3 * parent - grandparent;
        grandparent = parent;
        parent = curr;
    }
    return curr;
}

【讨论】:

    【解决方案4】:

    试试:

    int a=1, b=1; 
    for (b=1; b < 10000; b+=a ){ 
     System.out.print(a+" "+b+" "); 
     a+=b;
    }
    

    【讨论】:

      【解决方案5】:

      以下是不使用递归的方法。

          package fib;
      
          public class fib {
      
                  public static void main(String[] args) {
                          int first  = 1;
                          int second = 1;
                          int thrid  = 2;
                          System.out.format("0, %d, %d, %d", first, second, thrid);
                          while ( thrid < 1000 ) {
                                  first  = second;
                                  second = thrid;
                                  thrid  = first + second;
                                  System.out.format(", %d", thrid);
                          }
                  }
          }
      

      输出:

      0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597
      

      【讨论】:

      • 也许删除 TODO?
      【解决方案6】:

      请参阅algorithm 3 了解如何执行此操作,您可以使用 Binet 的公式在不递归的情况下执行此操作,复制如下:

      import java.lang.Math;
      import java.math.BigInteger;
      import java.math.BigDecimal;
      import java.math.MathContext;
      import java.math.RoundingMode;
      class f3c {
      // This program calculates the nth fibonacci number
      // using alrogirhtm 3C: Binet's formula with rounding
      //
      // compiled: javac f3c.java
      // executed: java f3c n
      //
      
        // Method f3c.isqrt(n) finds the inverse root of n using the following
        // recurrent equation: y(n+1) = 0.5*y(n)*[3 - x*y(n)^2]
        // It is faster than typical Newton-Raphson square root finding because
        // it does not use division.
        // Funny how Java implemented exponentiation by repeated squaring
        // for BigDecimals, but did not implement any sort of square root.
       private static BigDecimal isqrt(BigDecimal x, MathContext mc) {
           BigDecimal guess = new BigDecimal(1/Math.sqrt(x.doubleValue()));
           BigDecimal three = new BigDecimal(3);
           BigDecimal half = new BigDecimal(0.5);
           BigDecimal oldguess;
           do{ oldguess = guess;
               guess = half.multiply(guess.multiply(
                         three.subtract(x.multiply(guess.pow(2)))), mc);
           } while (oldguess.compareTo(guess) != 0);
      
           return guess;
       }
      
       // method f3c.fib(n) calculates the nth fibonacci number
       // as floor( phi^n/sqrt(5) + 1/2), where phi = (1+sqrt(5.0))/2;
       private static BigInteger fib(int n) {
          MathContext mc = new MathContext(n/2, RoundingMode.HALF_DOWN);
          BigDecimal is5 = isqrt(new BigDecimal("5"), mc);
          BigDecimal one = BigDecimal.ONE;
          BigDecimal half = new BigDecimal(0.5);
          BigDecimal phi = half.multiply(one.add(one.divide(is5, mc)));
          return phi.pow(n, mc).multiply(is5).toBigInteger();
       }
      
       // Method f3c.f(n) handles the negative arguments: F(-n) = F(n)*(-1)^(n+1)
       private static BigInteger f(int n) {
          if(n<0)
             return (n%2==0) ? fib(-n).negate() : fib(-n);
          else
             return fib(n);
       }
      
       // Method f3c.f_print(n) prints the nth Fibonacci number
       private static void fib_print(int n) {
        System.out.println(n + "th Fibonacci number is " + f(n));
       }
       // Method f3c.main is the program entry point
       // It makes sure the program is called with one commandline argument
       // converts it to integer and executse fib_print
       // If the conversion fails or if the number of arguments is wrong,
       // usage information is printed
       public static void main(String argv[]) {
        try {
            if(argv.length == 1) {
                fib_print(Integer.parseInt(argv[0]));
                System.exit(0);
            }
        } catch (NumberFormatException e) { }
        System.out.println("Usage: java f3c <n>");
        System.exit(1);
       }
      }
      

      但是,如果您只想将 while 循环转换为 for 循环,则一般原则是,如下代码:

      int var = 0;
      while (var != n) {
          ...
          var++;
      }
      

      ... 变成下面的 for 循环:

      for (int var = 0; i != n; i++) {
           ...
      }
      

      【讨论】:

        【解决方案7】:

        在这里很傻,你怎么能在 shell 中做到这一点:

        red@cricket:~$ ./fib.sh 
        0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
        red@cricket:~$ cat fib.sh 
        #!/bin/sh
        
        first=0
        second=1
        echo -n "$first, $second, "
        thrid=`expr $first + $second`
        echo -n $thrid 
        while [ $thrid -lt 100 ]
        do
                first=$second
                second=$thrid
                thrid=`expr $first + $second`
                echo -n ", $thrid"
        done
        echo ""
        

        哈哈!有些需要添加python答案!或递归bash 解决方案。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多