Wednesday, 5 July 2017

Java Code to identify whether the given two numbers are consecutive members or not in a fibonacci series.

Problem:

Given that two numbers d and e are suspected of being consecutive members of the Fibonacci sequence design an algorithm that will refute or confirm this conjecture.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FibonacciSeries2 {

int n;
int d;
int e;
List<Integer> numbers = new ArrayList<Integer>();
boolean areConsecutiveMembers = false;

public static void main(String[] args) {
FibonacciSeries2 fibonacciSeries2 = new FibonacciSeries2();
fibonacciSeries2.getTheNumbers();
fibonacciSeries2.generateFibonacciSeries();
fibonacciSeries2.printFibonacciSeries();
fibonacciSeries2.verifyConsecutiveMember();
fibonacciSeries2.printTheResult();
}

public void getTheNumbers(){
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
n = s.nextInt();
System.out.println("enter d value");
d = s.nextInt();
System.out.println("enter e value");
e = s.nextInt();
s.close();
}

public void generateFibonacciSeries(){
numbers.add(0);
numbers.add(1);
for(int i = 2; i<n; i++){
numbers.add(i, numbers.get(i-2) + numbers.get(i-1));
}
}

public void printFibonacciSeries(){
System.out.println("The fibonacci series is: " + numbers);
}

public void verifyConsecutiveMember(){
for(int j = 0; j< n-1; j++){
if(numbers.get(j) == d && numbers.get(j+1) == e){
areConsecutiveMembers = true;
}
}
}

public void printTheResult(){
System.out.println("are d and e values are consecutive members in fibonacci series??  " + areConsecutiveMembers);
}

}


Output:

enter the n value
10
enter d value
5
enter e value
3
The fibonacci series is: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
are d and e values are consecutive members in fibonacci series??  false


enter the n value
10
enter d value
8
enter e value
13
The fibonacci series is: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
are d and e values are consecutive members in fibonacci series??  true


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...