숫자 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) {
// add x where y is odd.
if (y % 2 == 1)
result = (result + x) % mod;
// Multiply x with 2
x = (x * 2) % mod;
// Divide y by 2
y /= 2;
}
return result % mod;
}
long long int nfactprod(long long int num){
// Initialize product and fact with 1
long long int product = 1, fact = 1;
long long int MOD = 1e9 + 7;
for (int i = 1; i <= num; i++) {
// to find factorial for every iteration
fact = mulmod(fact, i, MOD);
// product of first i factorials
product = mulmod(product, fact, MOD);
//when product divisible by MOD return 0
if (product == 0)
return 0;
}
return product;
}
int main(){
long long int num = 3;
printf("%lld \n", (nfactprod(num)));
return 0;
} 출력
위의 코드를 실행하면 다음 출력이 생성됩니다 -
12