Write a function f(a,b)
that returns a mod b
given the constraints:
- you can't use division in any way
f(a,b)
is always positive, eg:f(-1,5) = 4
- it performs reasonably well for values of ~
10e50
fora
andb
Write a function f(a,b)
that returns a mod b
given the constraints:
f(a,b)
is always positive, eg: f(-1,5) = 4
10e50
for a
and b
If I may call the function ?
instead:
1234567890123456789012345678901234
a?b|a<0=(a+b)?b|a>b=(a-b)?b|0<1=a
Elseway:
f a b|a<0=f(a+b)b|a>b=f(a-b)b|0<1=a
a
is negative (it will just return a
unchanged).
\$\endgroup\$
0<1
is shorter than True
\$\endgroup\$
Regex modulo
sub f{($a,$b)=@_;$_=1x$a;s/^(1{$b})+(1+)$/return length $2/e;}
Its now 66, thanks sepp2k!~
int m(int x,int y){x=(x<0)?-(x*y-x):x;while(x>=y) x-=y;return x;}
Abuse of the rules, please don't downvote: Mathematically, the modulus may be arbitrary large, because all moduli are equivalent. Thus, you may also use this, it WILL always return a positive result:
1234567890123456789012
a?b|a<0=(a+b)?b|True=a
And it will also always satisfy the equation
a?b = c <-> n*b + c = a
For some integer n.
f=->a,b{a==b&&0||a<b&&a+(a<0&&b||0)||(t=b;t<<=1until t>a;f[a-(t>>1),b])}
Uses recursion like a Binary Search to find the remainder.
Test
p f[106, 95]
p f[23, 2]
p f[-1, 5]
p f[20, 7]
p f[10**100, 3]
p f[4*10**200, 3123123]
11
1
4
6
1
823660
,>,<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>.
Takes a and b as bytes from standard input. Outputs one byte. Does not meet criteria to work with arbitrary size numbers, but to do so in brainfuck would not be simple.
f=lambda a,b:a if a<b else f(a-b,b)
Sadly, I can't use and
/or
short-circuiting here, so I have to do with one more byte.