Clumsy Factorial - Problem

The factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.

We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order.

For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.

However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.

Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11.

Given an integer n, return the clumsy factorial of n.

Input & Output

Example 1 — Small Number
$ Input: n = 4
Output: 7
💡 Note: clumsy(4) = 4 * 3 / 2 + 1 = 12 / 2 + 1 = 6 + 1 = 7
Example 2 — Larger Number
$ Input: n = 10
Output: 12
💡 Note: clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1 = 11 + 7 - 7 + 3 - 2 = 12
Example 3 — Minimum Case
$ Input: n = 1
Output: 1
💡 Note: clumsy(1) = 1 (no operations needed)

Constraints

  • 1 ≤ n ≤ 104

Visualization

Tap to expand
Clumsy Factorial INPUT n = 4 Decreasing Sequence: 4 3 2 1 Operator Rotation: * / + - Cycle: * / + - * / + - ... Floor division used ALGORITHM STEPS 1 Build Expression 4 * 3 / 2 + 1 2 Multiply First 4 * 3 = 12 3 Floor Divide 12 / 2 = 6 4 Add Remaining 6 + 1 = 7 Order of Operations: ((4 * 3) / 2) + 1 = (12 / 2) + 1 = 6 + 1 FINAL RESULT clumsy(4) = 7 Verification 4 * 3 / 2 + 1 = 12 / 2 + 1 = 7 OK Output: 7 Expected: 7 Key Insight: The clumsy factorial applies operators in rotation: *, /, +, - cycling through the sequence. Standard order of operations applies: multiply and divide (left to right) BEFORE add and subtract. Division is floor division (integer division truncating toward zero). Pattern recognition enables O(1) solution. TutorialsPoint - Clumsy Factorial | Optimal Solution
Asked in
Google 15 Amazon 8 Facebook 5
15.4K Views
Medium Frequency
~15 min Avg. Time
387 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen