Ask Your Question
2

'int' object has no attribute 'is_prime'

asked 7 years ago

Faisal gravatar image

updated 7 years ago

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/sage_server.py", 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
Preview: (hide)

1 Answer

Sort by » oldest newest most voted
4

answered 7 years ago

slelievre gravatar image

updated 7 years ago

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.

Preview: (hide)
link

Comments

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

Faisal gravatar imageFaisal ( 7 years ago )

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 7 years ago

Seen: 2,946 times

Last updated: Apr 10 '18