How far away is n to the next power of b?

32

2

Let n and b be positive integers larger than 1.

Output the distance from n to the next power of b.

For n=5 and b=3, the next power of 3 from 5 is 9 (3^2 = 9), so the output is 9 - 5 = 4.

For n=8 and b=2, the next power of 2 from 8 is 16 (2^4 = 16), so the output is 16 - 8 = 8. Note that n is a power of 2 in this example.

Testcases:

  n b output
212 2 44
563 5 62
491 5 134
424 3 305
469 8 43
343 7 2058
592 7 1809
289 5 336
694 3 35
324 5 301
  2 5 3

This is . Shortest answer in bytes wins. Standard loopholes apply.

Leaky Nun

Posted 2017-06-19T13:43:12.383

Reputation: 45 011

Answers

16

Jelly,  4  3 bytes

ạæċ

A dyadic link taking n on the left and b on the right and returning the result.

Try it online!

How?

ạæċ - Link: number n, number b | n,b ∈ ℕ
 æċ - ceiling n to the next power of b
ạ   - absolute difference between n and that

Jonathan Allan

Posted 2017-06-19T13:43:12.383

Reputation: 67 804

4Crossed out 4 is still regular 4 ;( – Uriel – 2017-06-19T13:53:50.573

2@Uriel But   ;) – HyperNeutrino – 2017-06-19T13:56:03.710

tfw your initially initial thought is "oh it's æċ!" instead of "oww this is sooo hard..." – Erik the Outgolfer – 2017-06-19T14:04:03.550

Oh it might not exist in the history, but I did change from a 4 byter. It was æċ_⁸ – Jonathan Allan – 2017-06-19T14:06:55.557

@JonathanAllan Since it wasn't in the history it didn't make sense and that's why I edited that out. – Erik the Outgolfer – 2017-06-19T14:11:12.233

8

x86-64 Assembly (Windows x64 Calling Convention), 14 13 bytes

An inefficient (but svelte!) iterative approach (with credit to @Neil for inspiration):

               HowFarAway PROC
6A 01             push   1
58                pop    rax         ; temp = 1
               Loop:
0F AF C2          imul   eax, edx    ; temp *= b
39 C8             cmp    eax, ecx
72 F9             jb     Loop        ; keep looping (jump) if temp < n
29 C8             sub    eax, ecx    ; temp -= n
C3                ret                ; return temp
               HowFarAway ENDP

The above function takes two integer parameters, n (passed in the ECX register) and b (passed in the EDX register), and returns a single integer result (in the EAX register). To call it from C, you would use the following prototype:

unsigned HowFarAway(unsigned n, unsigned b);

This is limited to the range of a 32-bit integer. It can be easily modified to support 64-bit integers by using the full long registers, but it would cost more bytes to encode those instructions. :-)

Cody Gray

Posted 2017-06-19T13:43:12.383

Reputation: 2 639

So, you can't set eax to 1 in fewer than 4 bytes? – Neil – 2017-06-19T15:31:43.677

Hmm… Not in any of the normal ways that a sane programmer would use, but you could push 1+pop rax in only 3 bytes. But… then you wouldn't have to skip the multiplication, so that would still be a reasonable savings because you could drop the jmp. – Cody Gray – 2017-06-19T15:35:11.500

Ah, I knew there had to be a way to golf a byte off! – Neil – 2017-06-19T15:41:47.320

You can do the same with the SysV calling convention on Linux, with a TIO demo.

– Digital Trauma – 2017-06-20T00:25:12.590

Of course you can. You can do it with any calling convention that passes at least the first two integer parameters in registers. System V, Win x64, Win32 __fastcall, etc. The registers just change, and I had to pick one. Coin came up "Windows". – Cody Gray – 2017-06-20T10:51:58.367

6

Dyalog APL, 10 bytes

2 bytes saved thanks to @ZacharyT

⊢-⍨⊣*1+∘⌊⍟

Try it online!

Takes n as right argument and b as left argument.

Calculates b⌊logbn + 1⌋ - n.

Uriel

Posted 2017-06-19T13:43:12.383

Reputation: 11 708

Nice, I was just about to post this exact solution – user41805 – 2017-06-19T14:03:00.330

@KritixiLithos I had hard time with the floor trick. you think it could be made into a train? – Uriel – 2017-06-19T14:12:17.710

Yeah, it can: ⊣-⍨⊢*1+∘⌊⍟⍨. – Zacharý – 2017-06-19T14:21:38.193

@ZacharyT nice one! – Uriel – 2017-06-19T14:25:33.413

I get ⊢-⍨⊣*1+∘⌊⍟ for 10 bytes but with swapped arguments so that n is the right argument and b is the left argument. I used ZacharyT's trick of 1+∘⌊ to get it down this far. – user41805 – 2017-06-19T14:27:11.327

@KritixiLithos I was just about to update this with the same one – Uriel – 2017-06-19T14:28:52.240

I was just about to comment the same thing! – Zacharý – 2017-06-19T14:29:40.090

@Jenny_mathy to handle cases where the number is an exact power of the base, like n=8 b=2. using ceiling would find 8-8 instead of 16-8. – Uriel – 2017-06-19T15:39:20.617

Good job. Nice teamwork. – Adám – 2017-06-19T16:07:28.120

6

C (gcc), 39 35 bytes

New undefined behavior thanks to Erik

f(n,b,i){for(i=b;b<=n;b*=i);n=b-n;}

Try it online!

cleblanc

Posted 2017-06-19T13:43:12.383

Reputation: 3 360

f(n,b,i){for(i=b;b<n;b*=i);n=b-n;} saves 5 bytes, and is supported by gcc – Erik the Outgolfer – 2017-06-19T14:16:29.023

@EriktheOutgolfer why not b-=n? – Leaky Nun – 2017-06-19T14:22:45.083

@LeakyNun Because it's the first argument you need to save the return value to. – Erik the Outgolfer – 2017-06-19T14:23:42.373

Umm, you didn't update the code. – Erik the Outgolfer – 2017-06-19T14:32:20.783

Can you do b-=n if you swap the order of b and n? – Zacharý – 2017-06-19T14:33:19.113

6

R, 38 34 bytes

pryr::f({a=b^(0:n)-n;min(a[a>0])})

Anonymous function. Stores all values of b to the power of everything in the range [0,n], subtracts n from each, subsets on positive values, and returns the min.

TIO has a non-pryr version, called as f(n,b); this version needs to be called as f(b,n).

Saved 4 bytes thanks to Jarko Dubbeldam, who then outgolfed me.

Try it online!

BLT

Posted 2017-06-19T13:43:12.383

Reputation: 931

Nice, way shorter than the recursion I had in mind. – JAD – 2017-06-20T09:43:49.540

pryr::f({a=b^(0:n)-n;min(a[a>0])}) is a few bytes shorter. – JAD – 2017-06-20T09:44:37.010

Thanks. I've had bad luck using pryr::f when I define a new variable in the function; looks like it works here. – BLT – 2017-06-20T14:41:11.383

2Hmm, it's always worth checking :) What annoys me is if you have something like sapply(x, sum) or whatever, that it adds sum to the arguments. – JAD – 2017-06-21T06:28:07.480

4

Cubix, 24 20 bytes

-4 bytes thanks to MickyT

Pwp.I|-.;)^0@O?|uq;<

Reads in input like n,b

Fits on a 2x2x2 cube:

    P w
    p .
I | - . ; ) ^ 0
@ O ? | u q ; <
    . .
    . .

Explanation:

I|I0 : read the input, push 0 (counter) to the stack

^w puts the IP to the right place for the loop:

  • Pp- : compute b^(counter), move n to top of stack, compute b^(counter) - n
  • ? : turn left if negative, straight if 0, right if positive
    • Positive: O@ : output top of stack (distance) and exit.
    • Negative : |? : proceed as if the top of the stack were zero
  • <;qu;) : point the IP in the right direction, pop the top of the stack (negative/zero number), move n to the bottom of the stack, u-turn, pop the top of the stack (b^(counter)) and increment the counter
  • IP is at ^w and the program continues.

Watch it online!

Try it online!

Giuseppe

Posted 2017-06-19T13:43:12.383

Reputation: 21 077

1Using your same procedure, just a different path Pwp.I|-.;)^0@O?|uq;< – MickyT – 2017-06-19T19:16:32.673

@MickyT genius! I feel like every time I submit a cubix answer, you come along and shave off four or five bytes... – Giuseppe – 2017-06-19T19:51:36.780

3

Haskell, 20 bytes

n%b=until(>n)(*b)1-n

Try it online!

until saves the day

xnor

Posted 2017-06-19T13:43:12.383

Reputation: 115 687

Augh, I knew there must have been a builtin for that. Nice. – vroomfondel – 2017-06-20T15:02:51.020

2

05AB1E, 9 8 bytes

sLmʒ‹}α¬

Try it online!

Explanation

s         # swap order of the inputs
 L        # range [1 ... n]
  m       # raise b to each power
   ʒ‹}    # filter, keep only the elements greater than n
      α   # calculate absolute difference with n for each
       ¬  # get the first (smallest)

Emigna

Posted 2017-06-19T13:43:12.383

Reputation: 50 798

1You beat me by a minute. That's exactly what I wrote, but I used ć instead of ¬. – Riley – 2017-06-19T13:54:45.223

@Riley: Also works with filter, but unfortunately doesn't save any bytes. – Emigna – 2017-06-19T13:58:32.317

1@Emigna unfortunately doesn't save any bytes saves byte(s)\ – Erik the Outgolfer – 2017-06-19T14:00:40.423

@EriktheOutgolfer: Yes, well. It was an additional change utilizing the weird way implicit input works that saved a byte :) – Emigna – 2017-06-19T14:01:42.473

Do the inputs have to be in that order? – Magic Octopus Urn – 2017-06-19T14:21:36.197

1@carusocomputing: Yes. It actually saves a byte to have them in the "wrong" order as I can reuse n implicitly, both in the filter comparison and the absolute difference calculation. – Emigna – 2017-06-19T14:33:57.330

2

MATL, 10 9 bytes

yy:YAn^w-

Try it online!

Explanation

Consider inputs 694 and 3 as an example.

y    % Implicitly take two inputs. Duplicate from below
     % STACK: 694, 3, 694
y    % Duplicate from below
     % STACK: 694, 3, 694, 3
:    % Range
     % STACK: 694, 3, 694, [1 2 3]
YA   % Base conversion (of 694 with "digits" given by [1 2 3]
     % STACK: 694, 3, [3 3 2 3 1 2]
n    % Number of elements
     % STACK: 694, 3, 6
^    % Power
     % 694, 729
w    % Swap
     % STACK: 729, 694
-    % Subtract. Implicitly display
^    % 35

Luis Mendo

Posted 2017-06-19T13:43:12.383

Reputation: 87 464

2

C, 42 40 bytes

Thanks to commenter @Steadybox for the tip

o;p(n,b){for(o=b;n>=b;)b*=o;return b-n;}

Govind Parmar

Posted 2017-06-19T13:43:12.383

Reputation: 828

2Using for instead of while saves two bytes: o;p(n,b){for(o=b;n>=b;)b*=o;return b-n;} – Steadybox – 2017-06-19T15:59:33.800

Suggest n/b instead of n>=b – ceilingcat – 2019-05-09T16:27:30.987

2

Mathematica, 24 bytes

#2^⌊1/#~Log~#2⌋#2-#&

thanks Martin

I/O

[343, 7]

2058

J42161217

Posted 2017-06-19T13:43:12.383

Reputation: 15 931

You can use 1/Log@## or #2~Log~#. Or even better swap the order of the inputs and use Log@##. – Martin Ender – 2017-06-19T14:06:18.587

And then #^Floor[...]# is shorter than #^(Floor[...]+1). And there's the Unicode operators for Floor as well. – Martin Ender – 2017-06-19T14:07:22.607

yes, yes of course.I'm working on all these.you are quick! – J42161217 – 2017-06-19T14:18:17.827

Don't forget Log@##! Actually, if you swap the argument order, #^⌊Log@##⌋#-#2& should be possible for -5 bytes (I think)! – CalculatorFeline – 2017-06-19T16:05:44.220

2

Java (OpenJDK 8), 42 bytes

Based on @GovindParmar's C answer.

n->b->{for(int o=b;n>=b;b*=o);return b-n;}

Try it online!

Bashful Beluga

Posted 2017-06-19T13:43:12.383

Reputation: 413

2

JavaScript (ES6), 29 bytes

Very similar to Rick's approach but posted with his permission (and some help saving a byte).

n=>b=>g=(x=b)=>x>n?x-n:g(x*b)

Try it

f=
n=>b=>g=(x=b)=>x>n?x-n:g(x*b)
oninput=_=>o.value=f(+i.value)(+j.value)()
o.value=f(i.value=324)(j.value=5)()
*{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
<label for=i>n: </label><input id=i type=number><label for=j>b: </label><input id=j type=number><label for=o>= </label><input id=o>

Shaggy

Posted 2017-06-19T13:43:12.383

Reputation: 24 623

2

R, 30 bytes

pryr::f(b^floor(log(n,b)+1)-n)

Evaluates to the function

function (b, n) 
b^floor(log(n, b) + 1) - n

Which takes the first power greater or equal than n, and then substracts n from that value.

Changed ceiling(power) to floor(power+1) to ensure that if n is a power of b, we take the next power.

JAD

Posted 2017-06-19T13:43:12.383

Reputation: 2 898

1

JavaScript (ES6), 31 bytes

f=(n,b,i=b)=>b>n?b-n:f(n,b*i,i)

Test cases:

f=(n,b,i=b)=>b>n?b-n:f(n,b*i,i)

console.log(f(212, 2)) // 44
console.log(f(563, 5)) // 62
console.log(f(491, 5)) // 134
console.log(f(424, 3)) // 305
console.log(f(469, 8)) // 43
console.log(f(343, 7)) // 2058
console.log(f(592, 7)) // 1809
console.log(f(289, 5)) // 336
console.log(f(694, 3)) // 35
console.log(f(324, 5)) // 301

Rick Hitchcock

Posted 2017-06-19T13:43:12.383

Reputation: 2 461

You can save a byte by currying (it didn't matter whether I tried currying both n and b or just n), because that saves you from having to pass n recursively. – Neil – 2017-06-19T14:17:46.723

Thanks @Neil, but I'm having trouble figuring out how to do that(?) – Rick Hitchcock – 2017-06-19T14:25:24.400

The two versions I came up with were n=>g=(b,p=b)=>p>n?p-n:g(b,p*b) and n=>b=>(g=p=>p>n?p-n:g(p*b))(b). – Neil – 2017-06-19T14:28:56.277

Would f=(n,i)=>g=(b=i)=>b>n?b-n:g(b*i) work for 30 bytes? It would need to be called like so: f(324,5)(). EDIT: Ah, @Neil beat me to it. – Shaggy – 2017-06-19T14:34:15.903

@Neil, thanks, I need more practice with currying. – Rick Hitchcock – 2017-06-19T14:42:13.783

@Shaggy, I think you should post your solution, but use currying to bring it down to 29 bytes: n=>i=>g=(b=i)=>b>n?b-n:g(b*i) – Rick Hitchcock – 2017-06-19T14:43:25.500

@RickHitchcock, as long as you don't feel it's too similar to yours? – Shaggy – 2017-06-19T14:48:50.460

Nope, go for it : ) – Rick Hitchcock – 2017-06-19T14:49:10.713

I've already upvoted. – Rick Hitchcock – 2017-06-19T15:01:25.810

1

Python,  42  41 bytes

f=lambda a,b,v=1:(a<v)*(v-a)or f(a,b,v*b)

A recursive function which, starting with v=1, repeatedly multiplies by b until it strictly exceeds a and then returns the difference.

Try it online!

Note: The result will never be zero so a>=v and f(a,b,v*b)or v-a may be replaced with (a<v)*(v-a)or f(a,b,v*b) without causing recursion errors.


Python 3, 37 bytes?

Using an idea of rici's...

f=lambda n,b:(n<b)*(b-n)or b*f(n/b,b)

which uses floating point arithmetic (hence results may stray from their true distance),
try that here.

Jonathan Allan

Posted 2017-06-19T13:43:12.383

Reputation: 67 804

@rici Nice, I think it may be OK to use floating point arithmetic. I'll add it as an alternative (another byte may be saved by switching forms due to b-n never being zero at the same time as n<b is true). – Jonathan Allan – 2017-06-19T19:56:19.937

1

Octave, 32 bytes

@(n,b)b^(fix(log(n)/log(b))+1)-n

Try it online!

Luis Mendo

Posted 2017-06-19T13:43:12.383

Reputation: 87 464

1

Octave, 26 bytes

@(n,b)b^sum(b.^(0:n)<=n)-n

Verify all test cases!

rahnema1

Posted 2017-06-19T13:43:12.383

Reputation: 5 435

1

Ruby, 38 bytes

Two different approaches:

->(n,b){p b**(Math.log(n,b).to_i+1)-n}

Try it online!

->(n,b){p b**(0..n).find{|x|b**x>n}-n}

Try it online!

Nnnes

Posted 2017-06-19T13:43:12.383

Reputation: 395

1

Japt, 9 bytes

_q}a@nVpX

Test it online!

Explanation

_  q}a@  nVpX
Z{Zq}aX{UnVpX}  // Ungolfed
                // Implicit: U, V = input integers
     aX{     }  // For each integer X in [0...1e9), take
          VpX   //   V to the power of X
        Un      //   minus U,
Z{  }           // and return the first one Z where
  Zq            //   Math.sqrt(Z) is truthy.
                //   Math.sqrt returns NaN for negative inputs, and 0 is falsy, so this is
                //   truthy iff Z is positive. Therefore, this returns the first positive
                //   value of V**X - U.
                // Implicit: output result of last expression

ETHproductions

Posted 2017-06-19T13:43:12.383

Reputation: 47 880

1... Wait. What? – Shaggy – 2017-06-19T17:04:09.237

@Shaggy I've added an explanation, hopefully this helps. – ETHproductions – 2017-06-19T19:41:32.367

1

Haskell, 31 bytes

f n b=[b^x-n|x<-[1..],b^x>n]!!0

Try it online!

vroomfondel

Posted 2017-06-19T13:43:12.383

Reputation: 2 094

1

Perl 6,  31 30  29 bytes

->\n,\b{(b,b* *...*>n).tail -n}

Test it (31)

->\n,\b{b**(log(n,b).Int+1)-n}

Test it (30)

{$^b**(log($^a,$b).Int+1)-$a}

Test it (29)

{($^b,$b* *...*>$^a).tail-$a}

Test it (29)

Brad Gilbert b2gills

Posted 2017-06-19T13:43:12.383

Reputation: 12 713

1

PARI/GP, 26 24 bytes

f(n,b)=b^logint(b*n,b)-n

Charles

Posted 2017-06-19T13:43:12.383

Reputation: 2 435

1

Brachylog, 7 bytes

^ʰ↙X>₁-

Try it online!

Takes input as a list [b, n].

    >₁     n is strictly less than
^ ↙X       some power of
 ʰ         b,
      -    and their difference is
           the output.

Unrelated String

Posted 2017-06-19T13:43:12.383

Reputation: 5 300

0

PHP>=7.1, 46 bytes

for([,$n,$b]=$argv;0>=$d=$b**$i++-$n;);echo$d;

PHP Sandbox Online

Jörg Hülsermann

Posted 2017-06-19T13:43:12.383

Reputation: 13 026

0

Python 3, 50 48 bytes

Thanks to EriktheOutgolfer for saving 2 bytes!

lambda n,b:b**-~int(math.log(n,b))-n
import math

Try it online!

Python doesn't have any fancy log or ceiling builtins, so I just went with the obvious approach with a little bit of golfing flair.

notjagan

Posted 2017-06-19T13:43:12.383

Reputation: 4 011

import math;lambda n,b:b**-~int(math.log(n,b))-n saves two bytes and is allowed per meta consensus. – Erik the Outgolfer – 2017-06-19T14:14:21.877

@EriktheOutgolfer ceil would not work. – Leaky Nun – 2017-06-19T14:15:32.457

@EriktheOutgolfer I wasn't using ceil because it doesn't work for powers of b, but as @Uriel pointed out importing before still saves a byte. – notjagan – 2017-06-19T14:18:07.777

You can reformat it to be completely fine: Try it online!. Just place the import after the lambda, and add f= in the header.

– Mr. Xcoder – 2017-06-19T15:27:53.973

@Mr.Xcoder Ah, you are correct! I don't know why that didn't occur to me. – notjagan – 2017-06-19T15:30:23.307

0

Lua, 74 73 Byte

A straight forward solution, I'm using 10 bytes to ensure that the arguments are treated as numbers, and not strings. Outputs to STDIN.

Edit: forgot to remove the space in w=1 n=n+0, saves one byte

n,b=...b=b+0p=b w=1n=n+0while p<=n do p=math.pow(b,w)w=w+1 end print(p-n)

Explained

Try it online!

n,b=...           -- unpack the argument into the variable n and b
b=b+0             -- set b's type to number
n=n+0             -- set n's type to number
p=b               -- set a variable to track the current value of the powered b
w=1               -- set the nth power
while p<=n        -- iterate untill the current power is greater or equals to n
do
  p=math.pow(b,w) -- raise b to the power w
  w=w+1           -- increment w
end
print(p-n)        -- outputs p minus the following power of b

Katenkyo

Posted 2017-06-19T13:43:12.383

Reputation: 2 857

I don't know Lua that well, but is the space between 1 and end needed? – Zacharý – 2017-06-19T14:40:55.500

@ZacharyT In Lua, hexadecimal numbers can be inlined if they start with a number, 1end would start to be interpreted as the number 1e then throw an error because 1en isn't a valid hexadecimal value. This only occure when the letter following the number is [abcdef] as other letters can't be interpreted as hexadecimal value -> w=1while doesn't throw an error. – Katenkyo – 2017-06-19T14:44:32.693

Welcome back to PPCG! – Leaky Nun – 2017-06-19T14:49:23.943

0

Python 2, 48 41 bytes

  • @Rod's loop simplification saved 7 bytes!

Full program without recursion or bit twiddling:

i=1;n,b=input()
while n>=i:i*=b
print i-n

Try it online!

Input format: n, b.

Mr. Xcoder

Posted 2017-06-19T13:43:12.383

Reputation: 39 774

You can simplify the loop to reduce 7 bytes

– Rod – 2017-06-19T15:27:00.750

@Rod Would have never thought of that :). Thanks a lot! – Mr. Xcoder – 2017-06-19T15:29:26.990

0

QBIC, 23 bytes

{p=:^q~p>:|_xp-b|\q=q+1

Takes parameter b first, then n.

Explanation

{       DO
p=:^q   SET p to input b (read as 'a' by QBIC fromt he cmd line) ** q (starts as 1)
~p>:    IF p exceeds 'n' (read as 'b' by QBIC fromt he cmd line)
|_xp-b| THEN QUIT, printing p minus b
\q=q+1  ELSE increase q, re-run

steenbergh

Posted 2017-06-19T13:43:12.383

Reputation: 7 772

0

Common Lisp, 73 bytes

(defun f(n b)(setq a b)(loop(when(> b n)(return(- b n)))(setq b(* b a))))

Try it online!

Steadybox

Posted 2017-06-19T13:43:12.383

Reputation: 15 798

0

Japt, 16 bytes

This feels longer than it needs to be!

pÂ(MlV /MlU Ä)-V

Try it

Shaggy

Posted 2017-06-19T13:43:12.383

Reputation: 24 623

0

J, 17 bytes

[-~]^[:>.]^.[:>:[

Usage

   f =: [-~]^[:>.]^.[:>:[
   424 f 3
305

Explanation

Performs pow(b, ceil(log(n+1))) where log has base b.

ljeabmreosn

Posted 2017-06-19T13:43:12.383

Reputation: 341

0

dc, 23 bytes

snsb1[lb*dln!<F]dsFxln-

I had hoped to be able to use Z to count digits in a given radix, but it seems to count only in decimal. And we might want a base larger than dc supports. So this takes the obvious approach of successively multiplying by b until a value larger than n is reached, at which point we subtract n and leave the result at top of stack.

Annoyingly, we need !< rather than > comparison because the condition excludes an answer of 0.

Demo

for i in '212 2' '563 5' '491 5' '424 3' '469 8' '343 7'\
         '592 7' '289 5' '694 3' '324 5' '2 5' \
         '12345678901234567890 1000000'
do printf '%s => ' "$i"; dc -e '?rsnsb1[lb*dln!<F]dsFxln-p' <<<"$i"
done
212 2 => 44
563 5 => 62
491 5 => 134
424 3 => 305
469 8 => 43
343 7 => 2058
592 7 => 1809
289 5 => 336
694 3 => 35
324 5 => 301
2 5 => 3
12345678901234567890 1000000 => 999987654321098765432110

Toby Speight

Posted 2017-06-19T13:43:12.383

Reputation: 5 058

0

AWK, 34+2 bytes

{for(n=$2;n<=$1;n*=$2){}$0=n-$1}1

Try it online!

Requires the -M option for arbitrary precision to handle the 12345678901234567890 1000000 => 999987654321098765432110 case.

The non-loop version requires the same number of bytes:

$0=$2^(int(log($1)/log($2)+1))-$1

Robert Benson

Posted 2017-06-19T13:43:12.383

Reputation: 1 339

Aahhh... I see that I may not need the 2 bytes for the "large" answer, since I accidentally grabbed Toby Speight's inputs rather than the original inputs. Oh well. This should allow it to work for all cases. – Robert Benson – 2017-06-20T15:55:49.137

0

TXR Lisp, 51 bytes

(defun f(n b)(-[(ginterate(op >= n)(op * b)1)-1]n))

Legend: ginterate, op.

Kaz

Posted 2017-06-19T13:43:12.383

Reputation: 372

0

APL(NARS), 13 chars, 26 bytes

{-⍺-⍵*1+⌊⍵⍟⍺}

test:

  f←{-⍺-⍵*1+⌊⍵⍟⍺}
  212 f 2
44
  563 f 5 
62
  592 f 7
1809

RosLuP

Posted 2017-06-19T13:43:12.383

Reputation: 3 036

0

JavaScript (ES6), 49 bytes

f=(n,b)=>b**(m=Math).floor(m.log(n)/m.log(b)+1)-n

Naruyoko

Posted 2017-06-19T13:43:12.383

Reputation: 459

0

Forth (gforth), 45 bytes

: f >r 1 begin i * 2dup < until rdrop - abs ;

Try it online!

Code Explanation

: f          \ start a new word definition
  >r         \ store b on the return stack for quick access
  1          \ create a counter to store powers of b
  begin      \ start an indefinite loop
    i *      \ multiply the counter by b
    2 dup <  \ duplicate the counter and n. Check if n is less than the counter
  until      \ if it is, end the loop
  rdrop      \ remove b from the return stack
  - abs      \ subtract and get absolute value (avoid negative)
;            \ end the word definition

reffu

Posted 2017-06-19T13:43:12.383

Reputation: 1 361