Write a Java code snippet to calculate the sum of the first 100 numbers in the Fibonacci sequence
Fibonnaci numbers follow this rule:
Here is my Java code snipet (as image and as text, so you can copy):
/** © 2012 interviewqa4java.blogspot.com*/
package iqa4java;
public class Fibonacci {
/**
* Write a Java code snippet to calculate the sum of the first 100 numbers in the
* Fibonacci sequence.
*/
public static void main(String[] args) {
System.out.println("Sum of the first 100 numbers in the Fibonacci sequence= "
+getFibonacciSum(100));
}
public static long getFibonacciSum(int sequenceSize){
long sum, fb0=0, fb1=1, fb2;
sum=fb0+fb1;
for (int i = 2; i < sequenceSize; i++) {
fb2= fb1 + fb0;
sum+=fb2;
fb0=fb1;
fb1=fb2;
}
return sum;
}
}
Fibonnaci numbers follow this rule:
- F(0) = 0;
- F(1) = 1;
- F(n) = F(n-1) + F(n-2), n ≥ 2, n is integer
Here is my Java code snipet (as image and as text, so you can copy):
package iqa4java;
public class Fibonacci {
/**
* Write a Java code snippet to calculate the sum of the first 100 numbers in the
* Fibonacci sequence.
*/
public static void main(String[] args) {
System.out.println("Sum of the first 100 numbers in the Fibonacci sequence= "
+getFibonacciSum(100));
}
public static long getFibonacciSum(int sequenceSize){
long sum, fb0=0, fb1=1, fb2;
sum=fb0+fb1;
for (int i = 2; i < sequenceSize; i++) {
fb2= fb1 + fb0;
sum+=fb2;
fb0=fb1;
fb1=fb2;
}
return sum;
}
}
No comments:
Post a Comment
Please, before starting to comment, evaluate if what you want to write is useful, respectful and positive. A kid may read this also.
Give a good example!