Calculate the inverse modulus

18

4

The task:

Output a value for x, where a mod x = b for two given values a,b.

Assumption

  • a and b will always be positive integers
  • There won't always be a solution for x
  • If multiple solutions exist, output at least one of them.
  • If there aren't any solutions, output nothing or some indication that no solutions exist.
  • Built-ins are allowed (not as fun as other mathematical approaches)
  • Outputs are always integers

Examples

A, B >> POSSIBLE OUTPUTS

5, 2 >> 3
9, 4 >> 5
8, 2 >> 3, 6
6, 6 >> 7, (ANY NUMBER > 6)
8, 7 >> NO SOLUTION
2, 4 >> NO SOLUTION
8, 5 >> NO SOLUTION
10,1 >> 3, 9

This is , so lowest bytes wins.

Graviton

Posted 2017-05-16T19:48:31.100

Reputation: 2 295

Can it error if no solution is found? – clap – 2017-05-17T03:14:28.723

@ConfusedMr_C Technically that does indicate no solution, so yes. – Graviton – 2017-05-17T20:55:06.643

Answers

11

JavaScript, 28 27 26 24 23 bytes

a=>b=>(a-=b)?a>b&&a:b+1

Try it online!

false indicates no solution.

-1 thanks @Arnauld

eush77

Posted 2017-05-16T19:48:31.100

Reputation: 1 280

Nicely done and nicely golfed. – Shaggy – 2017-05-16T20:54:49.887

So, to call it, you need to give the outer function a name, say f=..., then call f(8)(3)? That seems a little bit cheaty? The normal way to call a function would be f(8,3), which would make your function definition longer? – Steve Bennett – 2017-05-17T11:56:49.897

3

@SteveBennett True, the definition is curried, which means it must be called like (8)(3), but there is a consensus on PPCG that that's allowed. You don't have to give it a name though.

– eush77 – 2017-05-17T12:10:09.617

Ugh, for a very, very weak definition of "consensus". Most comments were "I don't like it, but I don't have a clear argument against it". How gross. – Steve Bennett – 2017-05-17T12:12:48.470

1@SteveBennett It's amusing how you think 26 vs -15 is anything but a clear consensus. Good luck trying to dispute. – eush77 – 2017-05-17T12:25:02.517

A consensus is not the same thing as a vote count, in many contexts. It involves things like the weight of argument, who is taking each position, etc. I see a weak argument by analogy "well, I guess if it's ok for Haskell, it's ok for Javascript" and an awful lot of discomfort with that outcome. – Steve Bennett – 2017-05-17T12:48:54.807

1@SteveBennett how is 55 to 1 a weak consensus? – Cyoce – 2017-05-24T17:16:13.967

Did you even read my two previous comments where I explained that? – Steve Bennett – 2017-05-24T22:57:13.637

6

MATL, 6 bytes

tQ:\=f

Try it online! Or verify all test cases.

Explanation

Consider inputs 8, 2 as an example.

t    % Implicit input. Duplicate                STACK: 8, 8
Q    % Add 1                                    STACK: 8, 9
:    % Range                                    STACK: 8, [1 2 3 4 5 6 7 8 9]
\    % Modulo                                   STACK: [0 0 2 0 3 2 1 0 8]
=    % Implicit input. Equality comparison      STACK: [0 0 1 0 0 1 0 0 0]
f    % Indices of nonzeros. Implicit display    STACK: [3 6]

Luis Mendo

Posted 2017-05-16T19:48:31.100

Reputation: 87 464

5

Python 2, 40 34 bytes

-6 bytes thanks to Bubbler

lambda a,b:[(a==b)*-~a,a-b][a>b*2]

Try it online!

Rod

Posted 2017-05-16T19:48:31.100

Reputation: 17 588

334 bytes: lambda a,b:[(a==b)*-~a,a-b][a>b*2] – Bubbler – 2018-10-02T06:55:49.210

4

Jelly, 5 bytes

‘R⁸%i

Returns the minimal valid x or 0 is there is none.

Try it online!

Dennis

Posted 2017-05-16T19:48:31.100

Reputation: 196 637

3

Groovy, 48 bytes (using built-in):

{a,b->Eval.me(a+"g").modInverse(Eval.me(b+"g"))}

Eval.me(...+"g") - Affixes "g" to the input, making it a BigInteger.

modInverse(...) - Performs the inverse modulo operation.


Java 8, 70 bytes

{a,b->return BigInteger.valueOf(a).modInverse(BigInteger.valueOf(b));}

Magic Octopus Urn

Posted 2017-05-16T19:48:31.100

Reputation: 19 422

3

R, 33 28 bytes

pryr::f(match(b,a%%1:(a+1)))

Try it online!

-4 bytes thanks to Jarko Dubbeldam.

-1 byte thanks to Giuseppe.

Returns NA if there is no solution. TIO doesn't have the pryr library installed, so the code at that link uses function(a,b) instead.

Nitrodon

Posted 2017-05-16T19:48:31.100

Reputation: 9 181

pryr::f(which(a%%1:(a+1)==b)) is 4 bytes shorter. – JAD – 2017-05-17T09:21:51.353

you can also drop another byte by using match(b,a%%1:(a+1)), which returns NA for a missing value. – Giuseppe – 2017-05-17T15:47:04.563

1

Jelly, 11 10 bytes

³%_⁴
r‘ÇÐḟ

A full program taking the two positive integers, a and b, and printing a list of the integer solutions between min(a,b)+1 and max(a,b)+1 inclusive.

Try it online!

Jonathan Allan

Posted 2017-05-16T19:48:31.100

Reputation: 67 804

1

Mathematica 36 Bytes

a_±b_:=Select[Range[9a],a~Mod~#==b&]

Input:

5 ± 2
9 ± 4
8 ± 2
6 ± 6
8 ± 7
2 ± 4
8 ± 5
10 ± 1

Output:

{3}
{5}
{3, 6}
{7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, \
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, \
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54}
{}
{}
{}
{3, 9}

Kelly Lowder

Posted 2017-05-16T19:48:31.100

Reputation: 3 225

When using these extended ASCII operators in a binary form, they need a space in front when being defined, otherwise the parser throws an error. So it would have to be a_ ±b_. But it's shorter to use Cases instead of Select an an unnamed function anyway: Cases[Range[9#],x_/;#~Mod~x==#2]& – Martin Ender – 2017-05-17T08:56:53.343

1

Haskell, 33 bytes

Crashes with code.hs: out of memory (requested ??? bytes) if there is no solution (times out on TIO before that):

a!b=[x|x<-[b+1..],mod(a-b)x<1]!!0

Try it online!

Thanks at Ørjan Johansen for spotting a mistake!

ბიმო

Posted 2017-05-16T19:48:31.100

Reputation: 15 345

This gives wrong answers for the test cases where b divides a. – Ørjan Johansen – 2018-10-02T03:11:51.040

1

C# (Mono C# compiler), 57 56 26 bytes

Port of Rod's Python answer. Thanks to W W for -1 byte.

HUGE thanks to Kevin Cruijssen for -30 bytes.

a=>b=>a-b>b?a-b:a==b?a+1:0

Try it online!

Epicness

Posted 2017-05-16T19:48:31.100

Reputation: 81

1Welcome to the site! It looks like you can removed the space after return. – Post Rock Garf Hunter – 2018-10-02T03:19:15.537

Welcome to PPCG! For non-recursive C# answers it's always best and shortest to use a lambda function (i=>{/*code here*/}). In this case however, since you have 2 inputs, it can be a currying lambda function to save an additional byte (a=>b=>{/*code here*/} instead of (a,b)=>{/*code here*/}). Also, you can remove the parenthesis around your if-checks. In total, without changing any of your functionality, it becomes a=>b=>a-b>b?a-b:a==b?a+1:0 26 bytes

– Kevin Cruijssen – 2018-10-03T09:58:59.303

Also, if you haven't seen it yet, Tips for golfing in <all languages> and Tips for golfing in C# might both be interesting to read through. Enjoy your stay! :)

– Kevin Cruijssen – 2018-10-03T10:00:47.440

Thank you all for the tips, I will keep these in mind when golfing in the future. – Epicness – 2018-10-03T12:02:00.337

0

Pyth, 16 bytes

hhx!0mqeQ%hQdShh

Try it online!

All test cases

Takes input as [a, b], errors if no solution found. Will revise if erroring isn't allowed.

clap

Posted 2017-05-16T19:48:31.100

Reputation: 834

0

Axiom, 147 128 bytes

g(a:PI,c:PI):Union(List PI,Stream INT)==(a<c=>[];r:=a-c;r=0=>expand((a+1..)::UniversalSegment INT);[b for b in divisors(r)|b>c])

ungolf it and test

--a%b=c return all possible b
f(a:PI,c:PI):Union(List PI, Stream INT)==
    a<c=>[]
    r:=a-c
    r=0=>expand((a+1..)::UniversalSegment INT)
    [b  for b in divisors(r)|b>c]

(3) -> [[i,j,g(i,j)] for i in [5,9,8,6,8,2,8,10] for j in [2,4,2,6,7,4,5,1]]
   (3)
   [[5,2,[3]], [9,4,[5]], [8,2,[3,6]], [6,6,[7,8,9,10,11,12,13,14,15,16,...]],
    [8,7,[]], [2,4,[]], [8,5,[]], [10,1,[3,9]]]
                                                      Type: List List Any

This would find all the solution even the infinite set solution...

RosLuP

Posted 2017-05-16T19:48:31.100

Reputation: 3 036

0

APL (Dyalog Unicode), 19 bytes

A←{(⍳⍵+1)/⍨⍺=⍵|⍨⍳⍵+1}

Try it online!

Golfing in progress...

user41805

Posted 2017-05-16T19:48:31.100

Reputation: 16 320

0

Mathematica, 28 bytes

Which[#>2#2,#-#2,#==#2,#+1]&

alephalpha

Posted 2017-05-16T19:48:31.100

Reputation: 23 988

0

PHP>=7.1, 51 Bytes

for([,$a,$b]=$argv;++$x<2*$a;)$a%$x!=$b?:print$x._;

Online Version

Jörg Hülsermann

Posted 2017-05-16T19:48:31.100

Reputation: 13 026

0

Pip, 9 bytes

a%,a+2@?b

Takes the two numbers as command-line arguments. Outputs the smallest solution, or nil if no solution exists. Try it online!

Explanation

           a, b are cmdline args (implicit)
  ,a+2     Range from 0 up to but not including a+2
a%         Take a mod each of those numbers
           (Note that a%0 returns nil; it emits a warning, but only if warnings are turned on)
      @?b  Find the index of the first occurrence of b in this list, or nil if it doesn't occur
           Autoprint (implicit)

For example, with input of 8 and 2:

   a+2   10
  ,      [0 1 2 3 4 5 6 7 8 9]
a%       [() 0 0 2 0 3 2 1 0 8]

The 0-based index of the first occurrence of 2 in this list is 3, which is our solution.

DLosc

Posted 2017-05-16T19:48:31.100

Reputation: 21 213

0

J, 14 bytes

(->]){-,~=*1+]

Try it online!

Translation of Rod's Python 2 solution.

How it works

The rare cases where a J code can be directly translated into Python.

(->]){-,~=*1+]  <=>  [(a==b)*(1+b),a-b][a-b>b]
         =*1+]        (a==b)*(1+b)
      -,~            [            ,a-b]
     {                                 [     ]
(->])                                   a-b>b

Bubbler

Posted 2017-05-16T19:48:31.100

Reputation: 16 616

0

Japt, 13 bytes

UµV ?U>V©U:ÒV

Try it online!

Translation of eush77's JS solution.

The code is just (U-=V)?U>V&&U:-~V when transpiled to JS, where U and V are the two input values.

Bubbler

Posted 2017-05-16T19:48:31.100

Reputation: 16 616

0

Ruby, 31 bytes

->a,b{(1..a+1).find{|x|a%x==b}}

Try it online!

G B

Posted 2017-05-16T19:48:31.100

Reputation: 11 099

0

Japt, 7 bytes

(Eventually) Outputs undefined if there's no solution.

@%X¥V}a

Try it here

Shaggy

Posted 2017-05-16T19:48:31.100

Reputation: 24 623

0

Perl 6, 23 bytes

{grep $^a%*==$^b,^$a+2}

Try it online!

Anonymous code block that returns a list of possible values from 2 up to a+1

Jo King

Posted 2017-05-16T19:48:31.100

Reputation: 38 234

0

ORK, 566 bytes

When this program starts:
I have a inputter called I
I have a number called a
I have a number called b
I is to read a
I is to read b
I have a mathematician called M
M's first operand is a
M's second operand is b
M is to subtract
I have a number called n
n is M's result
M's first operand is b
M's second operand is n
M is to compare
I have a scribe called W
If M says it's less then W is to write n
If M says it's less then W is to write "\n"
M's second operand is a
M is to compare
If M says it's equal then W is to write a
If M says it's equal then W is to write a

Try it online!

Objects R Kool. Luckily, however, I didn't need to use any (besides the built-in ones) for this task.

JosiahRyanW

Posted 2017-05-16T19:48:31.100

Reputation: 2 600

0

F#, 40 bytes

let m a b=Seq.find(fun x->a%x=b){1..a+1}

Try it online!

Pretty straight-forward. Throws a System.Collections.Generic.KeyNotFoundException if no solution can be found.

You could also modify it to Seq.tryFind, which will return an int option, with None if no solution could be found.

Ciaran_McCarthy

Posted 2017-05-16T19:48:31.100

Reputation: 689

0

05AB1E, 7 bytes

>Lʒ¹s%Q

Try it online or verify all test cases.

Explanation:

>          # First (implicit) input + 1
 L         # Create a range [1, n]
  ʒ        # Filter; only keep elements where:
   ¹s%     #  The first input modulo this value
      Q    #  Equals the second (implicit) input

Kevin Cruijssen

Posted 2017-05-16T19:48:31.100

Reputation: 67 575

0

Java 8, 26 bytes

a->b->a-b>b?a-b:a==b?a+1:0

Port of @Epicness' C# answer, after I golfed it a bit more.

Try it online.

Kevin Cruijssen

Posted 2017-05-16T19:48:31.100

Reputation: 67 575

0

><>, 21 bytes

Same trick as most posted solutions. First, we prepare all necessary values on the stack and then check the comparisons.

::r::{-:{)?nr=?!;1+n;

Try it online!

PidgeyUsedGust

Posted 2017-05-16T19:48:31.100

Reputation: 631

0

Whispers v2, 128 bytes

> Input
> Input
>> 1²
>> (3]
>> 1%L
>> L=2
>> Each 5 4
>> Each 6 7
>> L⋅R
>> Each 9 4 8
> {0}
>> {10}
>> 12∖11
>> Output 13

Try it online!

Returns a set of all possible solutions, and the empty set (i.e. \$\emptyset\$) when no solution exists.

How it works

Unsurprisingly, it works almost identically to most other answers: it generates a list of numbers and checks each one for inverse modulus with the argument.

If you're familiar with how Whispers' program structure works, feel free to skip ahead to the horizontal line. If not: essentially, Whispers works on a line-by-line reference system, starting on the final line. Each line is classed as one of two options. Either it is a nilad line, or it is a operator line.

Nilad lines start with >, such as > Input or > {0} and return the exact value represented on that line i.e > {0} returns the set \$\{0\}\$. > Input returns the next line of STDIN, evaluated if possible.

Operator lines start with >>, such as >> 1² or >> (3] and denote running an operator on one or more values. Here, the numbers used do not reference those explicit numbers, instead they reference the value on that line. For example, ² is the square command (\$n \to n^2\$), so >> 1² does not return the value \$1^2\$, instead it returns the square of line 1, which, in this case, is the first input.

Usually, operator lines only work using numbers as references, yet you may have noticed the lines >> L=2 and >> L⋅R. These two values, L and R, are used in conjunction with Each statements. Each statements work by taking two or three arguments, again as numerical references. The first argument (e.g. 5) is a reference to an operator line used a function, and the rest of the arguments are arrays. We then iterate the function over the array, where the L and R in the function represent the current element(s) in the arrays being iterated over. As an example:

Let \$A = [1, 2, 3, 4]\$, \$B = [4, 3, 2, 1]\$ and \$f(x, y) = x + y\$. Assuming we are running the following code:

> [1, 2, 3, 4]
> [4, 3, 2, 1]
>> L+R
>> Each 3 1 2

We then get a demonstration of how Each statements work. First, when working with two arrays, we zip them to form \$C = [(1, 4), (2, 3), (3, 2), (4, 1)]\$ then map \$f(x, y)\$ over each pair, forming our final array \$D = [f(1, 4), f(2, 3), f(3, 2), f(4, 1)] = [5, 5, 5, 5]\$

Try it online!


How this code works

Working counter-intuitively to how Whispers works, we start from the first two lines:

> Input
> Input

This collects our two inputs, lets say \$x\$ and \$y\$, and stores them in lines 1 and 2 respectively. We then store \$x^2\$ on line 3 and create a range \$A := [1 ... x^2]\$ on line 4. Next, we jump to the section

>> 1%L
>> L=2
>> Each 5 4
>> Each 6 7

The first thing executed here is line 7, >> Each 5 4, which iterates line 5 over line 4. This yields the array \$B := [i \: \% \: x \: | \: i \in A]\$, where \$a \: \% \: b\$ is defined as the modulus of \$a\$ and \$b\$.

We then execute line 8, >> Each 6 7, which iterates line 6 over \$B\$, yielding an array \$C := [(i \: \% \: x) = y \: | \: i \in A]\$.

For the inputs \$x = 5, y = 2\$, we have \$A = [1, 2, 3, ..., 23, 24, 25]\$, \$B = [0, 1, 2, 1, 0, 5, 5, ..., 5, 5]\$ and \$C = [0, 0, 1, 0, 0, ..., 0, 0]\$

We then jump down to

>> L⋅R
>> Each 9 4 8

which is our example of a dyadic Each statement. Here, our function is line 9 i.e >> L⋅R and our two arrays are \$A\$ and \$C\$. We multiply each element in \$A\$ with it's corresponding element in \$C\$, which yields an array, \$E\$, where each element works from the following relationship:

$$E_i = \begin{cases} 0 & C_i = 0 \\ A_i & C_i = 1 \end{cases}$$

We then end up with an array consisting of \$0\$s and the inverse moduli of \$x\$ and \$y\$. In order to remove the \$0\$s, we convert this array to a set (>> {10}), then take the set difference between this set and \$\{0\}\$, yielding, then outputting, our final result.

caird coinheringaahing

Posted 2017-05-16T19:48:31.100

Reputation: 13 702

-1

C#, 53 bytes (83 with function heading)

static int F(int a, int b){
    for(int i=1;i<=a+1;i++){if(a%i==b)return i;}return 0;
}

Try It Online

First try at codegolf. Probably not the best language to use, nor the most efficient coding.

Alex

Posted 2017-05-16T19:48:31.100

Reputation: 1

5Remove the unnecessary whitespace to save about 10 or more bytes – Mr. Xcoder – 2017-05-17T04:38:34.470