Suppose we have a number a, we have to find n, such that factorial of n (n!) is same as a. As we know, the factorial n = n * (n - 1) * (n - 2) * ... * 1. If there is no such integer n then return -1. So, if the input is like a = 120, then the output will be 5. To solve this, we will follow these steps −
Let us see the following implementation to get better understanding − ExampleLive Demo import math class Solution: def solve(self, a): i,num=0,1 L=[] while i < a : i=math.factorial(num) L.append(i) num+=1 if a in L : return L.index(a)+1 else : return -1 ob = Solution() print(ob.solve(120)) Input120 Output5
Updated on 23-Sep-2020 07:23:39
So the question comes like this, I'm new to python: def factorial_cap(num): For positive integer n, the factorial of n (denoted as n!), is the product of all positive integers from 1 to n inclusive. Implement the function that returns the smallest
I'm pretty sure this is the right function for factorial def. But I just couldn't figure out, instead of getting the 'total value', how can I just get the right output as I posted example above? Btw, should I use 'return' at the end of def, or it does not matter in this case? Teaching Kids Programming – Two Algorithms to Compute Inverse Factorials
Teaching Kids Programming: Videos on Data Structures and Algorithms The factorial of a number n is defined as n! = n * (n – 1) * (n – 2) * … * 1. Given a
positive integer a, return n such that n! = a. If there is no integer n that is a factorial, then return -1. Constraints Example 2 Inverse Factorial by DividingTry dividing N by 2, 3, 4… until we can’t or the dividend is 1.
class Solution: def solve(self, a): if a == 1: return 1 if a <= 0: return -1 i = 2 while a > 1: if a % i != 0: return -1 a /= i i += 1 return i - 1 Inverse Factorial by MultipicationTry multiply the product by 2, 3, 4, until the number is bigger or equal to N. When it is bigger, the given number is not a factorial number, otherwise it is.
class Solution: def solve(self, a): if a == 1: return 1 if a <= 0: return -1 s = 1 i = 2 while s < a: s *= i i += 1 return i - 1 if s == a else -1 –EOF (The Ultimate Computing & Technology Blog) — GD Star Rating 343 words The Permanent URL is: Teaching Kids Programming – Two Algorithms to Compute Inverse Factorials (AMP Version) |