Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java bội số thứ n của một số trong dãy Fibonacci


Để tìm bội số thứ n của một số trong dãy Fibonacci, mã Java như sau:

Ví dụ

public class Demo{    public static int position(int pos, int num){       long val_1 = 0, val_2 = 1, val_3 ;       int i = 2;       while(i != 0){          val_3 = val_1 + val_2;          val_1 = val_2;          val_2 = val_3;          if(val_2 % pos == 0){             return num * i;          }          i++;       }       return 0;    }    public static void main(String[] args){       int n = 10;       int k = 9;       System.out.print("Position of 10th multiple of 9 in the Fibonacci number list is ");       System.out.println(position(k, n));    } }

Kết quả

Position of 10th multiple of 9 in the Fibonacci number list is 120

Lớp Demo chứa hàm position tính số Fibonacci. Trong main, số cần bội trong dãy Fibonacci định nghĩa. Hàm gọi với tham số liên quan. Dữ liệu hiển thị trên console.