Ask Your Question
1

Inconsistency in function return value

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

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?

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted
2

answered 2020-03-11 19:44:56 +0100

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 $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
2

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

vdelecroix gravatar image

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

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
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

Stats

Asked: 2020-03-11 15:44:41 +0100

Seen: 344 times

Last updated: Mar 11 '20