1

Can someone explain why this code works with the sample number 13195, but crashes when I use the problem's number

num = 13195

def isprime(num):
  for i in range(2,num):
    if num % i == 0:
      ans = i
  return ans

print isprime(isprime(isprime(num)))
Victor Lazaro
  • 545
  • 2
  • 6
  • 16
  • 1
    Why are you calling `isprime(isprime(isprime(num)))`? Shouldn't it just be one call? – Rushy Panchal Apr 30 '16 at 20:36
  • 1
    Can you perhaps quote the assignment. Have you considered input `num=1`: it will return `None`... – Willem Van Onsem Apr 30 '16 at 20:37
  • Because it's so inefficient, find another algorithm (ex : https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) – Ouss4 Apr 30 '16 at 20:38
  • Would be helpful what the program is supposed to do, or what the "problem's number" is. At least add a link, so we don't have to ask google. – tobias_k Apr 30 '16 at 21:01
  • @tobias_k the problem is as follows: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? https://projecteuler.net/problem=3 – Victor Lazaro May 01 '16 at 02:26

2 Answers2

2

In Python 2, range constructs a list. So the program is trying to contain an enormous list in memory, and it can't. Use xrange which will generate the numbers on demand for iteration instead of all at once.

You also need to end the loop early or it will spend forever checking so many numbers. So once you find a divisor, use it to divide the original number and make it smaller and thus manageable.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

You need to assign a default value to ans.

When the input number is a prime number, the program never assigns anything to the variable ans. So that, when the function tries to return that variable, it is not actually defined.

JoseKilo
  • 2,343
  • 1
  • 16
  • 28