Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Challenges

Post History

66%
+2 −0
Challenges Print the modular multiplicative inverse / virtual fractions

Pyth, 16 bytes .^RtJ^2yTyJ%2S97 Try it online! This solution uses Euler's formula, which states that if a is coprime to m, a^(phi(m)-1) = a^-1 mod m where phi(m) is the totient function, t...

posted 9mo ago by isaacg‭

Answer
#1: Initial revision by user avatar isaacg‭ · 2024-03-01T20:53:14Z (9 months ago)
# [Pyth], 16 bytes

    .^RtJ^2yTyJ%2S97

[Try it online!][TIO-lt94lmtp]

This solution uses [Euler's formula](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Using_Euler's_theorem), which states that if a is coprime to m,

    a^(phi(m)-1) = a^-1 mod m

where phi(m) is the totient function, the number of integers in the range [1, m-1] that are coprime to m. For a power of 2, this is m/2.

Using this formula, I calculate the modular inverse of the odd numbers 1-97 with the modulus 2^21, because it makes the code shorter.

    .^RtJ^2yTyJ%2S97
                 S97    Generate the list 1, 2, ..., 97
               %2       Take every other number, the odd ones.
    .^R                 Map the modular exponentiation function over the list,
                        with the odd numbers as the base
        J^2yT           Calculate 2^20 and save it in J.
       t                Exponent of J-1
             yJ         Modulus of 2*J

[Pyth]: https://github.com/isaacg1/pyth
[TIO-lt94lmtp]: https://tio.run/##K6gsyfj/Xy8uqMQrzqgypNJL1SjY0vz//3/5BSWZ@XnF/3VTAA "Pyth – Try It Online"