给定数字N,任务是找到前N个阶乘以1000000007为模的乘积。阶乘表示当我们找到该数字以下所有数字的乘积(包括该数字)时,表示为!(感叹号),例如-4!= 4x3x2x1 = 24。
因此,我们必须找到n阶乘和1000000007模的乘积。
约束
1 ≤ N ≤ 1e6.
输入值
n = 9
输出结果
27
说明
1! * 2! * 3! * 4! * 5! * 6! * 7! * 8! * 9! Mod (1e9 + 7) = 27
输入值
n = 3
输出结果
12
说明
1! * 2! * 3! mod (1e9 +7) = 12
从i = 1到n递归找到阶乘并乘积所有阶乘
将所有阶乘的乘积乘以1e9 +7
返回结果。
In Fucntion long long int mulmod(long long int x, long long int y, long long int mod) Step 1→ Declare and Initialize result as 0 Step 2→ Set x as x % mod Step 3→ While y > 0 If y % 2 == 1 then, Set result as (result + x) % mod Set x as (x * 2) % mod Set y as y/ 2 Step 4→ return (result % mod) In Function long long int nfactprod(long long int num) Step 1→ Declare and Initialize product with 1 and fact with 1 Step 2→ Declare and Initialize MOD as (1e9 + 7) Step 3→ For i = 1 and i <= num and i++ Set fact as (call function mulmod(fact, i, MOD)) Set product as (call function mulmod(product, fact, MOD)) If product == 0 then, Return 0 Step 4→ Return product In Function int main() Step 1→ Declare and Initialize num = 3 Step 2→ Print the result by calling (nfactprod(num)) Stop
#include <stdio.h> long long int mulmod(long long int x, long long int y, long long int mod){ long long int result = 0; x = x % mod; while (y > 0) { //在y为奇数的地方加x。 if (y % 2 == 1) result = (result + x) % mod; //将x乘以2- x = (x * 2) % mod; //y除以2- y /= 2; } return result % mod; } long long int nfactprod(long long int num){ //初始化产品和事实 long long int product = 1, fact = 1; long long int MOD = 1e9 + 7; for (int i = 1; i <= num; i++) { //查找每次迭代的阶乘 fact = mulmod(fact, i, MOD); //第一个i阶乘的乘积 product = mulmod(product, fact, MOD); //当产品可被MOD整除时返回0- if (product == 0) return 0; } return product; } int main(){ long long int num = 3; printf("%lld \n", (nfactprod(num))); return 0; }
输出结果
如果运行上面的代码,它将生成以下输出-
12