Suppose we have a positive number n, we have to check whether n can be written as the sum of unique positive factorial numbers or not.
So, if the input is like n = 144, then the output will be True, as 4! + 5! = 24 + 120 = 144
To solve this, we will follow these steps −
fact := 1
res := a new list
x := 2
while fact <= n, do
insert fact at the end of res
fact := fact * x
x := x + 1
for i in range size of res -1 to 0, decrease by 1, do
if n >= res[i], then
n := n - res[i]
return true when n is same as 0
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): fact = 1 res = [] x = 2 while fact <= n: res.append(fact) fact = fact * x x += 1 for i in range(len(res)-1,-1,-1): if n>=res[i]: n-=res[i] return n==0 ob = Solution() print(ob.solve(144))
Input
144
Output
True