Search code examples
pythonfunctionrecursionfunctional-programmingmultiplication

How to solve factorial even numbers on the n number, then multiply them


For example there are 3 then the program will multiplying the first 3 factorials 2 x 4 x 6 = 48. For example if the user wants 3 then the program will multiply the first 3 factorials only and the sum value will decrease if the initial value is even. type int which contains a lot of even numbers that are wanted and will continue to grow in each recursive

Call:

Print (Value (number, initial))
print(value(3,0))

Output:

48

Explanation:

The first 3 even values are 2,4,6. So the results of their multiplication will be yield 48.

Sorry but what is wrong with my program:

def value(number,initial):

    while(initial<=(number)):

        print((initial*2), end="")

        initial = (initial+1)

        print("%d *" %(initial),end='')

        return initial * (str(value(number,initial)))


value(3,0)

Solution

  • How about using reduce?

    You could generate a range which full with the number starts with initial and the amount is the number

    from functools import reduce
    
    def value(number, initial):
        return reduce(lambda x, y: x * y, range(initial + 2, (initial + 2) + 2 * number, 2))
    
    print(value(3, 0))
    # 48