[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 历届试题 斐波那契

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

查看所有标签

猜你喜欢:

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

Practical Django Projects, Second Edition

Practical Django Projects, Second Edition

James Bennett / Apress / 2009 / 44.99

Build a django content management system, blog, and social networking site with James Bennett as he introduces version 1.1 of the popular Django framework. You’ll work through the development of ea......一起来看看 《Practical Django Projects, Second Edition》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具