import java.math.BigDecimal; import java.util.Scanner; import java.util.function.BinaryOperator; public class Fbnq { /** * 假设n为正整数,斐波那契数列定义为: * f(n) = 1, n < 3; * f(n) = f(n-1) + f(n-2), n>=3 * * 现在请你来计算f(n)的值,但是不需要给出精确值,只要结果的后六位即可。 * * 输入:一行,包含一个正整数n,且0<n<1000 * 输出:一行,f(n)的后6位(十进制,不足6位不补零) * @param args */ public static void main(String[] args) { Scanner s = new Scanner(System.in); int i = s.nextInt(); BigDecimal f2 = fb(i); String v = String.valueOf(f2); if (v.length() > 6) { String substring = v.substring(v.length() - 6); System.out.println(substring); }else { System.out.println(v); } } static BigDecimal fb(int num){ BigDecimal m = new BigDecimal(1); BigDecimal n = new BigDecimal(1); if (num == 1 || num == 2){ return m; } BigDecimal t = new BigDecimal(0); for (int i = 0; i <= num-3; i++) { t = m.add(n); m = n; n = t; } return t; } /*public static int fb1(int num) { if (num==1||num==2) { return 1; }else { return fb1(num - 1) + fb1(num - 2); } }*/ }
原文地址:https://www.cnblogs.com/412013cl/p/11768247.html
时间: 2024-10-12 08:13:12