How do you find the product of n numbers in python?

I have just started with Python programming language. I tried to write a function which takes input either a list or multiple integers to find their product. I am trying to find the product of first million natural numbers but its displaying an MemoryError.

def product(*arg):
    answer=1
    if type(arg) == tuple:
        arg=str(arg)
        arg=arg.lstrip('[(')
        arg=arg.rstrip('],)')
        arg=arg.split(',')
        for i in arg:
            answer*=int(i)
        return answer
    else:
        for i in arg:
            answer*=int(i)
        return answer

j=range(1,1000000,1)
j=list(j)
print(product(j))

Steps:

  • I convert the range object into list object if i am to pass a list as argument
  • Now, within the function, i try to split the tuple by converting it string.
  • I convert the resultant string into a list and then loop over the elements to find the product

Q1: How to avoid the memory error as i try to find the product of first Million natural numbers?

Q2 How to improve this code?

asked May 11, 2020 at 5:54

5

You can use a Generator in Python.

def generate_product():
    r = 1
    for i in range(1,1000000):
        r *= i + 1
        yield r

list(generate_product())[0]

It is more memory efficient and better in terms of performance.

Florian H

2,9152 gold badges12 silver badges25 bronze badges

answered May 11, 2020 at 6:30

How do you find the product of n numbers in python?

HarshitHarshit

1,41716 silver badges40 bronze badges

To calculate the product of all numbers from 1 to 1 million use a simple loop:

r = 1
for l in range(1,1000000):
    r*=(i+1)
print(res)

But keep in mind that the result will be a pretty big number. That means that your calculation might take long and the resulting number will need a lot memory.

EDIT Then i missread your question a little. This is a function that multiplies the elements in a list:

def multiply_list_elements(_list):
    result = 1
    for element in _list:
        result*=element
    return result

multiply_list_elements([1,2,3,4])

>>> 24

The memory error probably came from the huge number as @ZabirAlNazi calculated so nicely.

answered May 11, 2020 at 6:18

Florian HFlorian H

2,9152 gold badges12 silver badges25 bronze badges

1

All of the solution is fine, but one point to make - your question is equivalent to find the factorial of 1 million.

The number of digits of n! = log10(1) + log10(2) + ... log10(n)

import math
num_dig = 1
for i in range(1,1000000):
  num_dig += math.log10(i)
print(num_dig)

So, the number of digits in your answer is 5565703 (approx.).

That's only the final n, if you also want the intermediate results it will require squared memory O(m^2).

import math
ans = 1
for i in range(2,1000001):
  ans *= i
print(ans)

N.B: You can approximate with logarithms and Stirling numbers with faster run-time.

answered May 11, 2020 at 6:38

How do you find the product of n numbers in python?

Zabir Al NaziZabir Al Nazi

9,4273 gold badges24 silver badges49 bronze badges

A very simple solution would be:

    def prod_of():
        p=1
        for i in range(1,1000000):
            p* = i
        print(p)

answered May 11, 2020 at 8:48

Not the answer you're looking for? Browse other questions tagged python python-3.x list function out-of-memory or ask your own question.

How do you find the product of a number in Python?

Product of Digits of the number using Python.
Flow Chart Design..
Program or Solution. num = int(input("enter a number")) n = num. ... .
Output..
Program Explanation. initialize product is equal to 1..

How do you find the product of n numbers?

Product = n! ×(k+n)! n!

How do you multiply n numbers in Python?

In python, to multiply number, we will use the asterisk character ” * ” to multiply number. After writing the above code (how to multiply numbers in Python), Ones you will print “ number ” then the output will appear as a “ The product is: 60 ”. Here, the asterisk character is used to multiply the number.