通项公式求逆:
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 res2 = res - 1; int k = (int)(1.0/a*(Math.pow(temp1, res) - Math.pow(temp2, res))); int k2 = (int)(1.0/a*(Math.pow(temp1, res2) - Math.pow(temp2, res2))); int p = Math.min((int)Math.abs(x - k), (int)Math.abs(x - k2)); System.out.println(p); } }