Processing math: 100%

First time here? Check out the FAQ!

Ask Your Question
1

Inconsistency in function return value

asked 5 years ago

yasar11732 gravatar image
┌────────────────────────────────────────────────────────────────────┐
 SageMath version 9.0, Release Date: 2020-01-01                     
 Using Python 3.7.3. Type "help()" for help.                        
└────────────────────────────────────────────────────────────────────┘
sage: p = lambda x: (x - 1) / 2
sage: p(11)
5
sage: is_prime(5)
True
sage: is_prime(p(11))
False
sage:

In above example, is_prime function returns true when called like is_prime(5). However, when I give it p(11), which returns 5, as an argument, function returns false.

What is the reason for this behaviour, and how can I fix it?

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
2

answered 5 years ago

Juanjo gravatar image

In addition to the workarounds pointed by @vdelecroix, you can use the following one:

sage: ZZ(p(11)).is_prime()
True

You can also use the is_pseudoprime function, which does not require a previous coercion to the integers ring:

sage: is_pseudoprime(p(11))
True

For n264, if is_pseudoprime(n) returns True, it is very likely, but not sure, that n is prime. For n<264, is_pseudoprime(n) is True if and only if n is prime.

Preview: (hide)
link
2

answered 5 years ago

vdelecroix gravatar image

updated 5 years ago

The number (11 - 1) / 2 is a rational number not an integer

sage: parent(5)
Integer Ring
sage: parent((11 - 1) / 2)
Rational Field

As these objects are of different nature, the operation is_prime behaves differently on each of them. You should consider using one of the two workarounds

sage: is_prime( (11 - 1) // 2)  # floor division returns integer
True
sage: is_prime( Integer( (11 - 1) / 2 ) )  # conversion Rational -> Integer
True
Preview: (hide)
link

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: 5 years ago

Seen: 368 times

Last updated: Mar 11 '20