Ask Your Question

Inconsistency in function return value

asked 2020-03-11 09:44:41 -0600

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)
sage: is_prime(5)
sage: is_prime(p(11))

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 flag offensive close merge delete

2 answers

Sort by » oldest newest most voted

answered 2020-03-11 10:29:27 -0600

vdelecroix gravatar image

updated 2020-03-11 14:21:13 -0600

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
sage: is_prime( Integer( (11 - 1) / 2 ) )  # conversion Rational -> Integer
edit flag offensive delete link more

answered 2020-03-11 13:44:56 -0600

Juanjo gravatar image

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

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

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

sage: is_pseudoprime(p(11))

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.

edit flag offensive delete link more

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: 2020-03-11 09:44:41 -0600

Seen: 58 times

Last updated: Mar 11