O(1)通项公式解法:
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); double x = sc.nextDouble(); double a = Math.sqrt(5.0); double temp1 = (1.0 + a)/2.0; double temp2 = (1.0 - a)/2.0; double r = Math.log(x*a)/Math.log(temp1);//利用通项公式求这是第几项,忽略较小幂 int res = (int)Math.round(r); int k = (int)(1.0/a*(Math.pow(temp1, res) - Math.pow(temp2, res))); System.out.println((int)Math.abs(x - k)); } }