Reputation: 11
I am trying to create a Fibonacci sequence, starting with 1 and 2, that ends at 1000. That part I have figured out, but it also needs to return the sum of all odd numbers. I thought I figured it out, but I keep getting results that are incorrect.
Here is my code, appreciate any help I can get.
public class Fibonacci {
public static void main(String[] args) {
int n = 1000, t1 = 1, t2 = 2, odd = 0;
System.out.print("Fibonacci to " + n + ": ");
while (t1 <= n)
{
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
if (t1 % 2 != 0)
odd = odd + t1;
}
System.out.print("All odd numbers combined are: " + odd);
}
}
Upvotes: 1
Views: 469
Reputation: 1150
Since I see that someone else provided a decent answer, I enjoyed cooking up something else using List<>, Streams and recursion. You said that you're fairly new to programming, so don't hesitate to ask what's going on in my code. Although I learned mostly by googling myself.
public class Fibonacci {
private static final List<Integer> oddNumbers = new ArrayList<>();
public static void main(String[] args) {
generateFibonacciSequence(1000).forEach(number -> {
if (number < 1000){
System.out.println(number);
if (number % 2 != 0){
oddNumbers.add(number);
}
}
});
System.out.println("sum of odd numbers = " + oddNumbers.stream().mapToInt(oddNumber -> oddNumber).sum());
}
public static IntStream generateFibonacciSequence(int limit) {
AtomicInteger number = new AtomicInteger(0);
return IntStream.generate(
() -> fibonacci(number.incrementAndGet()))
.takeWhile((numberValue -> numberValue < limit));
}
private static int fibonacci(int position) {
if (position == 1 || position == 2) {
return 1;
}
return fibonacci(position - 2) + fibonacci(position - 1); //recursion
}
}
Upvotes: 0
Reputation: 7724
You are skipping values in your algorithm.
Before you add the current t1
value into odd
, you update it to the next.
The fibonacci sequece is:
t1 t2 t1 t2 t1 t2 t1 t2
1 2 3 5 8 13 21 34
Instead of adding 1, you are updating t1
to 3 before, so 1 is ignored.
Inside your while
loop, try this:
System.out.print(t1 + " + ");
if (t1 % 2 != 0) odd += t1;
t2 += t1;
t1 = t2 - t1;
Upvotes: 2