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 Show
Steps:
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.
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
HarshitHarshit 1,41716 silver badges40 bronze badges To calculate the product of all numbers from 1 to 1 million use a simple loop:
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:
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)
So, the number of digits in your answer is That's only the final
N.B: You can approximate with logarithms and Stirling numbers with faster run-time. answered May 11, 2020 at 6:38
Zabir Al NaziZabir Al Nazi 9,4273 gold badges24 silver badges49 bronze badges
A very simple solution would be:
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.
|