蓝桥杯 ADV-235 算法提高 阶乘差

版权声明:【https://github.com/liuchuo】大四在校生,水平有限,还望学长们多多包涵,Github真诚求Star~不甚感激!!!(卖萌脸ヾ(=^▽^=)ノ https://blog.csdn.net/liuchuo/article/details/84257967

问题描述
给定n和m以及p,保证n>=m,求(n!-m!)对p取余的结果。
输入格式
一行三个正整数n,m,p。
输出格式
一行一个非负整数表示结果。
样例输入
3 2 10
样例输出
4
数据规模和约定
n,m<=20,p<=10000.

分析:先取余再相减,减完为了避免出现负数的情况,加上p再取余~

#include <iostream>
using namespace std;
int n, m, p;
int f(int n){
    int ans = 1;
    for(int i = 1; i <= n; i++)
        ans = ans * i % p;
    return ans;
}
int main() {
    cin >> n >> m >> p;
    cout << (f(n)-f(m) + p) % p;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liuchuo/article/details/84257967