Ask Your Question

'int' object has no attribute 'is_prime'

asked 2018-04-09 16:43:39 +0100

Faisal gravatar image

updated 2018-04-09 16:48:13 +0100

Hi ... I am wondering why this code is not working

for number in range(20,30):
  if number.is_prime():
    print number

I got this error in Cocalc

Error in lines 1-3
Traceback (most recent call last):
  File "/cocalc/lib/python2.7/site-packages/smc_sagews/", line 1013, in execute
    exec compile(block+'\n', '', 'single') in namespace, locals
  File "", line 2, in <module>
AttributeError: 'int' object has no attribute 'is_prime'

However, it works when I change the code to

for number in range(20,30):
    if is_prime(number):
        print number
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2018-04-09 17:22:34 +0100

slelievre gravatar image

updated 2018-04-10 15:54:01 +0100

This is because range spits out Python integers, and not Sage integers.

Python integers are "machine integers", that are designed to be fast, but can only be used for standard operations, and don't know about the rich structure of the ring of integers.

You could use srange, which works like range but gives you Sage integers.

If you use range, then use ZZ(number).is_prime() to first convert the numbers to integers before applying the .is_prime() method.

What is_prime(number) does is to try and apply the .is_prime() method if it is available, and otherwise first convert the number to a Sage integer, then apply the .is_prime() method.

edit flag offensive delete link more


Thank you @slelievre so much for your detailed answer..

Faisal gravatar imageFaisal ( 2018-04-13 09:06:17 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2018-04-09 16:43:39 +0100

Seen: 2,410 times

Last updated: Apr 10 '18