第(N-2)和第(N-1)th的第N个输出和

时间:2014-02-28 06:19:29

标签: java for-loop while-loop

无论我尝试什么,我都无法想出这个问题,我可能只是在思考它,我能得到一些帮助吗?我已经尝试了各种不同的for循环,我可以;弄清楚如何获得这些值

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

我想这样做,因此它声明a + b,但我认为不可能

以下代码以Fibonacci而闻名,其中第N个输出是(N的总和) 2)th和(N-1)个值。编写for-expression来执行相同的任务。

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

7 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

您可以使用递归来执行此操作:

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

答案 2 :(得分:1)

如果您想使用循环,可以执行以下操作(借用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;
}

答案 3 :(得分:1)

尝试:

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

答案 4 :(得分:0)

如果没有递归,你就可以这样做。

    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

答案 5 :(得分:0)

请参阅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 (int var = 0; i != n; i++) {
     ...
}

答案 6 :(得分:0)

在这里如何愚蠢如何在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 ""

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