[Tutor] Tutor Digest, Vol 95, Issue 55

Steven D'Aprano steve at pearwood.info
Sun Jan 22 11:52:02 CET 2012


Shreesh bhat wrote:
> *Lucky Numbers*
> A number is called lucky if the sum of its digits, as well as the sum of
> the squares of its digits is a prime number. How many numbers between A and
> B are lucky?

Very little of this is relevant to your problem. In the future, please provide 
a short, self-contained, correct example that demonstrates the problem.

http://sscce.org/

Here is the shortest example I can see, a single line of code:

xrange(2**31-1, 2**31)

which gives the same error:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to int

(The error message itself can vary from version to version.)

Possible solutions:

* Don't use xrange, write your own generator which will do the job.

def my_xrange(start, stop):
     i = start
     while i < stop:
         yield i
         i += 1


This will work, but will be much slower.


* Scale your numbers from time to time, to avoid them getting too big.
* Can you rethink your algorithm and avoid needing such huge numbers?
* Just accept that your function can't handle such huge numbers.



> Traceback (most recent call last): File
> "/run-1327085301-1965755690/solution.py",
>  line 35, in li=map(islucky,xrange(startnum, endnum))
> OverflowError: Python int too large to convert to C long
> 
> -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> It shows this error for very large numbers or slows down with large numbers.


It slows down for large numbers because you have written a very inefficient 
isprime() function.



> I m using Ubuntu 32-bit.


What is more important than the version of your operating system is the 
version of Python.


> On Sun, Jan 22, 2012 at 4:24 AM, <tutor-request at python.org> wrote:
[snip hundreds of irrelevant lines]

Please do not reply to digest posts without deleting the unnecessary quoting, 
and setting the subject line appropriately.

You may find it useful to read this:

http://catb.org/esr/faqs/smart-questions.html



-- 
Steven


More information about the Tutor mailing list