Ask Your Question

Inconsistency in function return value

asked 2020-03-11 15:44:41 +0200

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 19:44:56 +0200

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

answered 2020-03-11 16:29:27 +0200

vdelecroix gravatar image

updated 2020-03-11 20:21:13 +0200

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

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 15:44:41 +0200

Seen: 294 times

Last updated: Mar 11 '20