[Java] 蓝桥杯PREV-29 历届试题 斐波那契

栏目: Java · 发布时间: 7年前

内容简介:问题描述斐波那契数列大家都非常熟悉。它的定义是:f(x) = 1 …. (x=1,2)

问题描述

斐波那契数列大家都非常熟悉。它的定义是:

f(x) = 1 …. (x=1,2)

f(x) = f(x-1) + f(x-2) …. (x>2)

对于给定的整数 n 和 m,我们希望求出:

f(1) + f(2) + … + f(n) 的值。但这个值可能非常大,所以我们把它对 f(m) 取模。

公式如下

但这个数字依然很大,所以需要再对 p 求模。

输入格式

输入为一行用空格分开的整数 n m p (0<n, m, p<10^18)

输出格式

输出为1个整数,表示答案

样例输入

2 3 5

样例输出

0

样例输入

15 11 29

样例输出

25

package prev29;
 
import java.math.BigInteger;
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long n = in.nextLong();
        long m = in.nextLong();
        BigInteger p = in.nextBigInteger();
        in.close();
 
        BigInteger f1 = new BigInteger("1");
        BigInteger f2 = new BigInteger("1");
        BigInteger fm = new BigInteger("1");
        for (long i = 3; i <= m; i++) {
            fm = f1.add(f2);
            f1 = f2;
            f2 = fm;
        }
 
        f1 = new BigInteger("1");
        f2 = new BigInteger("1");
        BigInteger sum = new BigInteger("2");
        BigInteger fn = new BigInteger("0");
        for (long i = 3; i <= n; i++) {
            fn = f1.add(f2);
            sum = sum.add(fn);
            f1 = f2;
            f2 = fn;
        }
 
        System.out.println(sum.mod(fm).mod(p));
    }
 
}
❤❤点击这里 -> 订阅PAT、蓝桥杯、GPLT天梯赛、LeetCode题解离线版❤❤ [Java] 蓝桥杯PREV-29 历届试题 斐波那契

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Elements of Statistical Learning

The Elements of Statistical Learning

Trevor Hastie、Robert Tibshirani、Jerome Friedman / Springer / 2009-10-1 / GBP 62.99

During the past decade there has been an explosion in computation and information technology. With it have come vast amounts of data in a variety of fields such as medicine, biology, finance, and mark......一起来看看 《The Elements of Statistical Learning》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

MD5 加密
MD5 加密

MD5 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具