Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project euler in python (#53)

Tags:

python

So I'm learning python so I'm going through some project euler problems. And I'm not sure if this is a python problem I'm having, or just me being retarded, but I seem to be getting the wrong answer for problem 53. Here's a link to the problem http://projecteuler.net/index.php?section=problems&id=53

and this is my code:


from math import factorial

def ncr(n,r):
    return (factorial(n)/(factorial(r)*factorial(n-r)))

i = 0

for x in range(1,100):
    for y in range(0,x):
        if(ncr(x,y) > 1000000):
            i=i+1

print i

I'm getting 3982 which is apparently the wrong answer. Is something wrong that I'm doing that's specific to python?

like image 846
Falmarri Avatar asked Jul 29 '10 09:07

Falmarri


People also ask

Is Project Euler free?

Otherwise, please Register – it's completely free! However, as the problems are challenging, then you may wish to view the Problems before registering. "Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics."

What is Project Euler net?

Project Euler (named after Leonhard Euler) is a website dedicated to a series of computational problems intended to be solved with computer programs. The project attracts graduates and students interested in mathematics and computer programming.

Where can I solve Project Euler problems?

You can now solve the classic Project Euler programming problems using the Rust language. Each of these problems comes with a user-friendly test suite. Here's the full Project Euler Rust GitHub repository. If you do not know Rust, and want to learn it, you can start with freeCodeCamp's interactive Rust course.

Does Project Euler show solutions?

Projecteuler-solutions provides merely a list of answers -- that is, it does not provide solutions or code for individual problems.


2 Answers

Considering the input from the problem specification: "It is not until n = 23, that a value exceeds one-million", you can make the range for the outer from 23 to 101:

for x in range(23,101):
  ...

Furthermore, n over k can be calculated faster without generating the three factorials:

def noverk(n,k):
  noverk=1
  if 2*k < n:
    k=n-k;
  for i in range(1,n-k+1):
    noverk *= (i+k)
    noverk /= i
  return noverk;
like image 84
Peter B. Avatar answered Sep 23 '22 12:09

Peter B.


range( a, b) does not include b.

like image 37
Katriel Avatar answered Sep 21 '22 12:09

Katriel