Given an integer N, the task is to find the MDAS factorial.
The general factorial of a no. N is given by :
Factorial(N) = (N)*(N-1)*(N-2)*(N-3)*(N-4)*(N-5)*(N-6)*(N-7)- – – – – -(3)*(2)*(1).
In MDAS factorial, instead of simply multiplying the numbers from N to 1, we perform four operations, Multiplication(*), Divide(/), Addition(+) and Subtraction(-) in a repeating pattern as shown below:
MDAS_Factorial(N) = (N) * (N-1) / (N-2) + (N-3) – (N-4) – – – – – upto 1.
By using the integers in decreasing order, we swap the multiplication operations for fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in the above order.
Input : N = 4 Output : 7 Explaination : MDAS_Factorial(4) = 4 * 3 / 2 + 1 = 7 Input : N = 10 Output : 12 Explaination : MDAS_Factorial(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1 = 12
Simple Approach: : The idea is to use a loop for each cycle of operations (*,/,+,-) and calculate the MDAS_Factorial of N. But this may work slow if N is very large. Time Complexity of this approach is O(N).
Efficient Approach :
If we observe carefully it can be concluded that:
- If N is less than or equal to 2 then answer will be N itself.
- If N is 3 OR N is 4, the answer is N + 3.
- If (N – 4) is completely divisible by 4, the answer is N + 1.
- If (N – 4) gives remainder 1 OR 2 while dividing by 4, the answer is N + 2.
- For the remaining values, the answer will be N – 1.
Below is the implementation of above approach
Time complexity: O(1)
Auxiliary space: O(1)
- Find the last digit when factorial of A divides factorial of B
- Sum of divisors of factorial of a number
- Factorial of a large number
- C Program for factorial of a number
- First digit in factorial of a number
- Program for factorial of a number
- Python Program for factorial of a number
- Smallest number with at least n digits in factorial
- Java Program for factorial of a number
- One line function for factorial of a number
- Number of digits in N factorial to the power N
- Find sum of digits in factorial of a number
- Smallest number S such that N is a factor of S factorial or S!
- Program to calculate the number of odd days in given number of years
- Smallest number with at least n trailing zeroes in factorial
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.