Problem Statement:
Mark wants to find the triple factorial of a given number N.
A triple factorial of a number N is the product of positive numbers less than or equal to that number and congruent to N modulo 3.
It means N!!! = N * (N-3) * (N-6) *... * (x+3) * x, where x is the smallest positive number which is congruent to N modulo 3.
Print the triple factorial for a given number N.
Note:
Function Description:
In the provided code snippet, implement the provided tripleFactorial(...) method to print the triple factorial for a given number N. You can write your code in the space below the phrase "WRITE YOUR LOGIC HERE".
There will be multiple test cases running so the Input and Output should match exactly as provided.
The base Output variable result is set to a default value of -404 which can be modified. Additionally, you can add or remove these output variables.
Input Format:
Sample Test Case:
Input:
10
Expected Output:
280
(Explanation for your understanding: 10*7*4*1 = 280)
Topics Involved / Prerequisites
Overview
The problem asks us to compute a custom "triple factorial" (N!!!), which is the product of all positive integers less than or equal to N that share the same remainder as N when divided by 3.
We can easily simulate this behavior by starting our current value at N and repeatedly multiplying our total while subtracting 3 from the current value, stopping when it drops below 1.
Approach
1. Base Case Check
The problem explicitly states that the triple factorial of 0 is 1. We must handle this as an immediate conditional check.
2. Iterative Multiplication
We initialize a result variable to 1. We then create a loop that starts at i = N and decrements by 3 at each step (i -= 3). The loop continues as long as i > 0.
3. Modulo Arithmetic
Because factorials grow exponentially large very quickly, we are required to return the answer modulo 10^9 + 7. To prevent integer overflow during the calculation, we must apply this modulo operation at every single multiplication step, not just at the very end.
Code Implementation (C++)
#include <iostream>
using namespace std;
int tripleFactorial(int N) {
if (N == 0) {
return 1;
}
long long result = 1;
long long MOD = 1000000007;
for (long long i = N; i > 0; i -= 3) {
// Multiply and apply modulo at each step to prevent overflow
result = (result * i) % MOD;
}
return result;
}
Time and Space Complexity