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

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.

# 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

• Crossed out 4 is still regular 4 ;( Commented Jun 19, 2017 at 13:53
• @Uriel But &nbsp; ;) Commented Jun 19, 2017 at 13:56
• tfw your initially initial thought is "oh it's æċ!" instead of "oww this is sooo hard..." Commented Jun 19, 2017 at 14:04
• Oh it might not exist in the history, but I did change from a 4 byter. It was æċ_⁸ Commented Jun 19, 2017 at 14:06
• @JonathanAllan Since it wasn't in the history it didn't make sense and that's why I edited that out. Commented Jun 19, 2017 at 14:11

## 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. :-)

• So, you can't set eax to 1 in fewer than 4 bytes?
– Neil
Commented Jun 19, 2017 at 15:31
• 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. Commented Jun 19, 2017 at 15:35
• Ah, I knew there had to be a way to golf a byte off!
– Neil
Commented Jun 19, 2017 at 15:41
• You can do the same with the SysV calling convention on Linux, with a TIO demo. Commented Jun 20, 2017 at 0:25
• 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". Commented Jun 20, 2017 at 10:51

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

• f(n,b,i){for(i=b;b<n;b*=i);n=b-n;} saves 5 bytes, and is supported by gcc Commented Jun 19, 2017 at 14:16
• @EriktheOutgolfer why not b-=n? Commented Jun 19, 2017 at 14:22
• @LeakyNun Because it's the first argument you need to save the return value to. Commented Jun 19, 2017 at 14:23
• Umm, you didn't update the code. Commented Jun 19, 2017 at 14:32
• Can you do b-=n if you swap the order of b and n? Commented Jun 19, 2017 at 14:33

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

• Nice, I was just about to post this exact solution Commented Jun 19, 2017 at 14:03
• @KritixiLithos I had hard time with the floor trick. you think it could be made into a train? Commented Jun 19, 2017 at 14:12
• Yeah, it can: ⊣-⍨⊢*1+∘⌊⍟⍨. Commented Jun 19, 2017 at 14:21
• @ZacharyT nice one! Commented Jun 19, 2017 at 14:25
• 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. Commented Jun 19, 2017 at 14:27

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

• Nice, way shorter than the recursion I had in mind.
Commented Jun 20, 2017 at 9:43
• pryr::f({a=b^(0:n)-n;min(a[a>0])}) is a few bytes shorter.
Commented Jun 20, 2017 at 9:44
• Thanks. I've had bad luck using pryr::f when I define a new variable in the function; looks like it works here.
– BLT
Commented Jun 20, 2017 at 14:41
• Hmm, 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.
Commented Jun 21, 2017 at 6:28

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

• Using your same procedure, just a different path Pwp.I|-.;)^0@O?|uq;< Commented Jun 19, 2017 at 19:16
• @MickyT genius! I feel like every time I submit a cubix answer, you come along and shave off four or five bytes... Commented Jun 19, 2017 at 19:51

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


Try it online!

until saves the day

• Augh, I knew there must have been a builtin for that. Nice. Commented Jun 20, 2017 at 15:02

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

• 1 byte shorter using %/%1 instead of floor() Commented May 1, 2022 at 7:28

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

• You beat me by a minute. That's exactly what I wrote, but I used ć instead of ¬. Commented Jun 19, 2017 at 13:54
• @Riley: Also works with filter, but unfortunately doesn't save any bytes. Commented Jun 19, 2017 at 13:58
• @Emigna unfortunately doesn't save any bytes *saves byte(s)* Commented Jun 19, 2017 at 14:00
• @EriktheOutgolfer: Yes, well. It was an additional change utilizing the weird way implicit input works that saved a byte :) Commented Jun 19, 2017 at 14:01
• @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. Commented Jun 19, 2017 at 14:33

# Java (OpenJDK 8), 42 bytes

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


Try it online!

# 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


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

# Mathematica, 24 bytes

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


thanks Martin

I/O

[343, 7]

2058

• You can use 1/Log@## or #2~Log~#. Or even better swap the order of the inputs and use Log@##. Commented Jun 19, 2017 at 14:06
• And then #^Floor[...]# is shorter than #^(Floor[...]+1). And there's the Unicode operators for Floor as well. Commented Jun 19, 2017 at 14:07
• yes, yes of course.I'm working on all these.you are quick! Commented Jun 19, 2017 at 14:18
• Don't forget Log@##! Actually, if you swap the argument order, #^⌊Log@##⌋#-#2& should be possible for -5 bytes (I think)! Commented Jun 19, 2017 at 16:05

# 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;}

• Using for instead of while saves two bytes: o;p(n,b){for(o=b;n>=b;)b*=o;return b-n;} Commented Jun 19, 2017 at 15:59
• Suggest n/b instead of n>=b Commented May 9, 2019 at 16:27

# Japt, 16 8 bytes

This feels longer than it needs to be! That's a bit better!

nVpUìV l


Try it

nVpUìV l     :Implicit input of integers U=n & V=b
n            :Subtract U from
Vp          :  Raise V to the power of
UìV       :    Convert U to a base-V digit array
l     :    Get the length


# AWK, 34 32+2 bytes

{for(n=$2;n<=$1;n*=$2);}$0=n-$11  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


After almost 5 years, saved 2 bytes in each formulation by removing unnecessary grouping symbols. Thanks @PaoloVlw

• 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. Commented Jun 20, 2017 at 15:55
• These save both versions 2 bytes each: {for(n=$2;n<=$1;n*=$2);}$0=n-$1 and $0=$2^int(log($1)/log($2)+1)-$1. Commented May 1, 2022 at 3:36
• @PauloVlw It's nice to know that someone is still interested in AWK. :) Commented May 3, 2022 at 18:27

# Desmos, 30 27 bytes

f(n,b)=b^{floor(log_bbn)}-n


Try It On Desmos

-3 thanks to @Aiden Chow and @Steffan

Gotta love using your favorite graphing calculator for code golf. Taken from the R answer.

# Python 2,  42 41  35 bytes

Saved 6 thanks to loopy walt! (A superior recursive algorithm.)

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


A recursive function which repeatedly integer divides by b until that yields 0 (n<1) yielding 1 (well, True which works like 1) at the tail and multiplies back up by b removing the remainder after division by b at each step. That is, we subtract n from b^k in base b, "digit" by "digit".

Try it online!

• tio.run/… is a bit shorter but having to output the result with format "%.0f" is probably cheating.
– rici
Commented Jun 19, 2017 at 19:40
• @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). Commented Jun 19, 2017 at 19:56
• 35 bytes (Python2) I believe. Commented May 4, 2022 at 22:37
• Much better, thanks @loopywalt (I think I'd have posted as my own if I'd seen this and written that!) Do let me know if you think there is a clearer description or if I have any mistakes. Commented May 5, 2022 at 19:01
• Not much glory to earn with very late answers... Re clarity, perhaps mention that we are basically subtracting (from b^k) n digit-by-digit in base b. Commented May 5, 2022 at 19:24

# Vyxal, 8 bytes

ɾe'¹>;hε


Try it Online!

Port of 05AB1E.

## How?

ɾe'¹>;hε
ɾ        # Inclusive range from one to (implicit) first input
e       # For each element, push it to the power of the (implicit) second input
'¹>;   # Filter for only elements greater than the first input
h  # Get the first item
ε # Get the absolute difference of the first item and the (implicit) first input


# 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

• 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
Commented Jun 19, 2017 at 14:17
• Thanks @Neil, but I'm having trouble figuring out how to do that(?) Commented Jun 19, 2017 at 14:25
• 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
Commented Jun 19, 2017 at 14:28
• 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. Commented Jun 19, 2017 at 14:34
• @Neil, thanks, I need more practice with currying. Commented Jun 19, 2017 at 14:42

# Octave, 32 bytes

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


Try it online!

# Octave, 26 bytes

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


Verify all test cases!

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

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


Try it online!

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

# PARI/GP, 26 24 bytes

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


# 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

• ... Wait. What? Commented Jun 19, 2017 at 17:04
• @Shaggy I've added an explanation, hopefully this helps. Commented Jun 19, 2017 at 19:41

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


# 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


# Husk, 6 bytes

≠Ω>¹*³


Try it online!

≠Ω>¹*³      # ¹ and ³ duplicate arguments ⁰ and ², so parses as:
≠Ω>⁰*²²⁰
# now:
Ω>⁰*²²     # Ω = Iterate function f until test result t is truthy, starting with x:
²     #     x is arg 2
*²      #     f is *² = times arg 2, so iterating generates power series of arg 2
>⁰        #     t is >⁰ = greater than arg 1
# then:
≠           # get the absolute difference to
⁰    # arg 1