# Inconsistency in function return value

┌────────────────────────────────────────────────────────────────────┐
│ 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?

edit retag close merge delete

Sort by » oldest newest most voted

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

more

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 $n\geq 2^{64}$, if is_pseudoprime($n$) returns True, it is very likely, but not sure, that $n$ is prime. For $n<2^{64}$, is_pseudoprime($n$) is True if and only if $n$ is prime.

more

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