N, bir sonraki b'nin gücüne ne kadar uzaklıktadır?


32

Şundan büyük pozitif tamsayılar olsun nve olsun .b1

İla bir nsonraki gücüne olan mesafeyi çıkarın b.

İçin n=5ve b=3, bir sonraki güç 3ile ilgili 5olan 9( 3^2 = 9), yani çıkış 9 - 5 = 4.

İçin n=8ve b=2, bir sonraki güç 2ile ilgili 8olan 16( 2^4 = 16), yani çıkış 16 - 8 = 8. Not nbir güçtür 2bu örnekte.

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

Bu . Bayt cinsinden en kısa cevap kazanır. Standart boşluklar uygulanır.

Yanıtlar:


16

Jöle ,  4  3 bayt

ạæċ

nSolda ve bsağda yer alan ve sonucu döndüren ikili bir bağlantı .

Çevrimiçi deneyin!

Nasıl?

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

4
4 çarpı 4 hala normal 4; (
Uriel

2
@Uriel But  ;)
HyperNeutrino

senin TfW başlangıçta ilk düşünce "ah öyle olduğunu æċ!" yerine "oww's sooo zor ..."
Outgolfer Erik

Ah, tarihte olmayabilir, ama 4 byte değişiklik yaptım. Öyleydiæċ_⁸
Jonathan Allan

@ JonathanAllan Tarihte olmadığından bir anlam ifade etmiyordu ve bu yüzden bunu düzenlemiştim.
Outgolfer Erik

8

x86-64 Meclisi ( Windows x64 Arama Sözleşmesi ), 14 13 bayt

Verimsiz (ama svelte!) Yinelemeli bir yaklaşım (İlham için @Neil kredisi ile):

               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

Yukarıdaki işlev n( ECXregister'da geçti ) ve b( register'da geçti) iki tamsayı parametresi alır EDXve tek bir tamsayı sonucu ( EAXregister'da) döndürür . C'den çağırmak için aşağıdaki prototipi kullanırsınız:

unsigned HowFarAway(unsigned n, unsigned b);

Bu, 32 bit tam sayı aralığı ile sınırlıdır. Tam uzun kayıtları kullanarak 64 bit tam sayıları desteklemek için kolayca değiştirilebilir, ancak bu komutları kodlamak daha fazla bayta mal olur. :-)


Yani, eax'i 4 bayttan daha az bir sürede 1'e ayarlayamazsınız?
Neil

Hmm… Aklı başında bir programcının kullanacağı normal yollardan hiçbirinde değil , sadece 3 baytta + kullanabilirsiniz . Ama… o zaman çarpımı atlamak zorunda kalmazsınız, böylece makul bir tasarruf olur çünkü düşersiniz . push 1pop raxjmp
Cody Gray

Ah, bir bayt golf oynamak için bir yol olması gerektiğini biliyordum!
Neil

Bir ile, Linux üzerinde SysV çağrı kuralı ile aynı yapabilirsiniz TIO demo .
Dijital Travma

Tabi ki yapabilirsin. Kayıtlarda en az ilk iki tamsayı parametresini geçen herhangi bir arama kuralıyla bunu yapabilirsiniz. System V, Win x64, Win32 __fastcall, vb. Kayıtlar değişti ve bir tane seçmek zorunda kaldım. Para "Windows" geldi.
Cody Gray

6

C (GCC) , 39 35 bayt

Erik sayesinde yeni tanımsız davranış

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

Çevrimiçi deneyin!


f(n,b,i){for(i=b;b<n;b*=i);n=b-n;}5 bayt kaydeder ve gcc tarafından desteklenir
Outgolfer Erik

@EriktheOutgolfer neden olmasın b-=n?
Leaky Rahim

@ LeakyNun Çünkü dönüş değerini kaydetmeniz gereken ilk argümandır.
Outgolfer Erik

Umm, kodu güncellemedin.
Outgolfer Erik

Bunu yapabilir misin b-=nsen sırasını takas eğer bve n?
Zacharı

6

Dyalog APL, 10 bayt

@ZacharyT sayesinde 2 bayt kurtarıldı

⊢-⍨⊣*1+∘⌊⍟

Çevrimiçi deneyin!

Alır nsağ argüman olarak ve bsol argümanı.

Hesaplar .b⌊logbn + 1⌋ - n


Güzel, tam olarak bu çözümü
yollamak üzereydim

@KritixiLithos Kat numarasıyla zor zamanlar geçirdim. bir tren haline getirilebileceğini mi düşünüyorsun?
Uriel

Evet, olabilir: ⊣-⍨⊢*1+∘⌊⍟⍨.
Zacharı

@ ZacharyT güzel bir!
Uriel

⊢-⍨⊣*1+∘⌊⍟10 bayt alırım ama değiştirilen argümanlarla bu yüzden ndoğru argüman ve bsol argüman. ZacharyT'nin numarasını 1+∘⌊bu ana kadar elde etmek için kullandım.
Kritixi Lithos

6

R , 38 34 bayt

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

Anonim işlev B'nin tüm değerlerini [0, n] aralığında her şeyin gücüne kaydeder, her birinden n çıkarır, pozitif değerleri alt eder ve min.

TIO, pryr olmayan bir versiyona sahiptir f(n,b); Bu sürüm olarak adlandırılması gerekiyor f(b,n).

Beni bayıltan Jarko Dubbeldam sayesinde 4 bayt kurtarıldı.

Çevrimiçi deneyin!


Güzel, aklımda olan özyinelemeden çok daha kısa.
JAD

pryr::f({a=b^(0:n)-n;min(a[a>0])})bir kaç bayt daha kısa.
JAD

Teşekkürler. İşlevde pryr::fyeni bir değişken tanımladığımda kötü şansım oldu ; burada çalışıyor gibi görünüyor.
BLT

2
Hmm, her zaman kontrol etmeye değer :) Argümanlara sapply(x, sum)eklediği gibi bir şey veya her neyse, beni rahatsız eden şey sum.
JAD

4

Cubix , 24 20 bayt

MickyT sayesinde -4 bayt

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

Gibi giriş okur n,b

2x2x2 küpüne uyar:

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

Açıklama:

I|I0 : girişi okuyun, yığına 0 (sayaç) basın

^w IP'yi döngü için doğru yere koyar:

  • Pp-: hesapla b^(counter), nyığının üstüne taşı, hesaplab^(counter) - n
  • ? : negatifse sola, düz ise 0, pozitif ise sağa dön
    • Olumlu:: O@yığının üst çıkış (mesafe) ve çıkış.
    • Negatif:: |?yığının tepesi sıfırmış gibi ilerleyin
  • <;qu;): IP'yi doğru yöne çevirin, yığının üstünü (negatif / sıfır numarası) açın, nyığının altına taşıyın , u dönüşü yapın, yığının üstünü ( b^(counter)) açın ve sayacı artırın
  • IP adresinde ^wve program devam ediyor.

Online izleyin!

Çevrimiçi deneyin!


1
Aynı prosedürü kullanarak, sadece farklı bir yolPwp.I|-.;)^0@O?|uq;<
MickyT

@MickyT dehası! Ben cubix cevap gönderdiğiniz her zaman gibi hissediyorum, sen ... boyunca ve tıraş dört ya da beş byte dökülmek
Giuseppe


2

05AB1E , 9 8 bayt

sLmʒ‹}α¬

Çevrimiçi deneyin!

açıklama

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)

1
Beni bir dakika dövdün. Ben de aynen öyle yazdım, ama ćyerine kullandım ¬.
Riley,

@Riley: Ayrıca filtre ile çalışır, ancak ne yazık ki herhangi bir bayt kaydetmez.
Emigna

1
@Emigna ne yazık ki herhangi bir byte kaydetmiyor * tasarruf bayt (lar) *
Erik Outgolfer

@EriktheOutgolfer: Evet, iyi. Bir bayt kazandıran garip bir şekilde örtük girdi çalışmalarını kullanan ek bir değişiklikti :)
Emigna

1
@carusocomputing: Evet. Aslında , hem filtre karşılaştırmasında hem de mutlak fark hesaplamasında dolaylı olarak tekrar kullanabildiğim için onları "yanlış" sıraya getirmek için bir bayt kaydeder n.
Emigna


2

MATL , 10 9 bayt

yy:YAn^w-

Çevrimiçi deneyin!

açıklama

Girdileri 694ve 3bir örnek olarak düşünün .

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

2

JavaScript (ES6), 29 bayt

Rick'in yaklaşımına çok benzer, ancak onun izni ile yayınlanmıştır (ve bir kısmı bayt kurtarmaya yardım eder).

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

Dene

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>


2

Mathematica, 24 bayt

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

teşekkürler 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@##.
Martin Ender

And then #^Floor[...]# is shorter than #^(Floor[...]+1). And there's the Unicode operators for Floor as well.
Martin Ender

yes, yes of course.I'm working on all these.you are quick!
J42161217

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

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

2
Using for instead of while saves two bytes: o;p(n,b){for(o=b;n>=b;)b*=o;return b-n;}
Steadybox

Suggest n/b instead of n>=b
ceilingcat

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.


1

JavaScript (ES6), 31 bytes

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

Test cases:


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

Thanks @Neil, but I'm having trouble figuring out how to do that(?)
Rick Hitchcock

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

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

@Neil, thanks, I need more practice with currying.
Rick Hitchcock







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

1
... Wait. What?
Shaggy

@Shaggy I've added an explanation, hopefully this helps.
ETHproductions

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.


tio.run/… is a bit shorter but having to output the result with format "%.0f" is probably cheating.
rici

@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



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

I don't know Lua that well, but is the space between 1 and end needed?
Zacharý

@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

Welcome back to PPCG!
Leaky Nun

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


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.


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

@EriktheOutgolfer ceil would not work.
Leaky Nun

@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

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

@Mr.Xcoder Ah, you are correct! I don't know why that didn't occur to me.
notjagan

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.