Sunday 23 July 2017

Java Code to Prove that consecutive Fibonacci numbers are relatively prime.

Problem:

It is well known that adjacent Fibonacci numbers do not share a common divisor greater than 1 (they are relatively prime). Design an algorithm and implement that tests this observation for the first n integers.

Solution:

package com.myprograms;

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

public class GCDOfFibonaciNumbers {

int n;
List<Integer> fibonacciList = new ArrayList<Integer>();

public static void main(String[] args) {
GCDOfFibonaciNumbers gcdOfFibonaciNumbers = new GCDOfFibonaciNumbers();
gcdOfFibonaciNumbers.getTheNumbers();
gcdOfFibonaciNumbers.fibonacciNumbers();
gcdOfFibonaciNumbers.findDivisors();
}

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

public void fibonacciNumbers(){
fibonacciList.add(0);
fibonacciList.add(1);
for(int i = 2; i<n;i++){
fibonacciList.add(fibonacciList.get(i-1) + fibonacciList.get(i-2));
}
System.out.println("the fibonacci numbers are " + fibonacciList);
}

public void findGCD(int largerNumber, int smallNumber){
System.out.print("the GCD of " + largerNumber +" and " + smallNumber + " is: ");
int reminder = largerNumber % smallNumber;
while(reminder != 0){
largerNumber = smallNumber;
smallNumber = reminder;
reminder = largerNumber % smallNumber;
}
System.out.println(smallNumber);
}

public void findDivisors(){
for(int i = 0; i<fibonacciList.size() - 1; i++){
findGCD(fibonacciList.get(i), fibonacciList.get(i+1));
}
}
}


Output:

enter the n value
15
the fibonacci numbers are [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
the GCD of 0 and 1 is: 1
the GCD of 1 and 1 is: 1
the GCD of 1 and 2 is: 1
the GCD of 2 and 3 is: 1
the GCD of 3 and 5 is: 1
the GCD of 5 and 8 is: 1
the GCD of 8 and 13 is: 1
the GCD of 13 and 21 is: 1
the GCD of 21 and 34 is: 1
the GCD of 34 and 55 is: 1
the GCD of 55 and 89 is: 1
the GCD of 89 and 144 is: 1
the GCD of 144 and 233 is: 1
the GCD of 233 and 377 is: 1

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...