To write a Java program for finding the nth multiple of a number in the Fibonacci series, we can follow the steps below:
First, we define a function that takes two integer arguments, n and k, where n is the index of the multiple we want to find, and k is the number we want to find multiples of.
We initialize two integer variables, a and b, to 0 and 1 respectively, as these are the first two numbers in the Fibonacci series.
We then loop from 2 to n, calculating each number in the Fibonacci series by adding the two previous numbers, and storing them in a and b.
Inside the loop, we check if a is a multiple of k using the modulo operator (%). If it is, we decrement n by 1. When n reaches 0, we return a.
If a is not a multiple of k, we continue the loop until we find the nth multiple of k in the Fibonacci series.
Here is the code for the program:
public static int nthFibonacciMultiple(int n, int k) { int a = 0; int b = 1; for (int i = 2; i <= n; i++) { int c = a + b; a = b; b = c; if (a % k == 0) { n--; if (n == 0) { return a; } } } return -1; }
This function returns the nth multiple of k in the Fibonacci series, or -1 if there is no such multiple.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.