整数対数


12

整数が与えられるとN , P > 1Mそのような最大の整数を見つけるP ^ M ≤ N

I / O:

入力は2つの整数Nとで与えられますP。出力は整数になりMます。

例:

4, 5 -> 0
33, 5 -> 2
40, 20 -> 1
242, 3 -> 4 
243, 3 -> 5 
400, 2 -> 8
1000, 10 -> 3

ノート:

入力は常に有効です。つまり、常に1より大きい整数になります。

クレジット:

名前の功績は@cairdcoinheringaahingにあります。最後の3つの例は@Nitrodonによるもので、説明を改善した功績は@Giuseppeにあります。


3
私たち(PPCGコミュニティ)は本当に小さなものについて過度にきびきびしているように見えるかもしれませんが、私のようなコメントは、誠実に、チャレンジを改善することを本当に意図しています!これが解決されたので、喜んで投票し、以前のコメントを削除しました。
ジュゼッペ

9
それが、The Sandboxにチャレンジを最初に投稿することをお勧めするもう1つの理由です。そうすることで、有用なフィードバックを受け取り、素晴らしいチャレンジを投稿し、はるかに少ない手間で(質疑応答やダウン投票など)質の高い回答を得ることができます。:)
ジュゼッペ

2
サンドボックスチャレンジに関するフィードバックを求めて、一般的なPPCGチャットルームにいつでも投稿して彼らにもう少し注目を集めることができます。
ジュゼッペ

12
浮動小数点演算に基づく現在の回答のほとんどすべては、丸め誤差のために(1000、10)のような単純な場合でも誤った結果を生成するため、別のテストケースを追加しました。
-nwellnhof

3
@MPWはすべての応答を削除し、私が行った提案は投稿に編集されたため、関連性がなくなりました。
ジュゼッペ

回答:


8

Brain-Flak、74バイト

(({}<>)[()])({()<(({})<({([{}]()({}))([{}]({}))}{})>){<>({}[()])}{}>}[()])

オンラインでお試しください!

これは、標準のBrain-Flak正整数除算アルゴリズムと同じ概念を使用します。

# Push P and P-1 on other stack
(({}<>)[()])

# Count iterations until N reaches zero:
({()<

  # While keeping the current value (P-1)*(P^M) on the stack:
  (({})<

    # Multiply it by P for the next iteration
    ({([{}]()({}))([{}]({}))}{})

  >)

  # Subtract 1 from N and this (P-1)*(P^M) until one of these is zero
  {<>({}[()])}{}

# If (P-1)*(P^M) became zero, there is a nonzero value below it on the stack
>}

# Subtract 1 from number of iterations
[()])


6

Excel、18バイト

=TRUNC(LOG(A1,A2))

A1で入力「n」、A2で入力「p」を受け取ります。


2バイトを節約INTする代わりに関数を使用できると思いますTRUNC
パジョン


3

Retina 0.8.2、35バイト

.+
$*
+r`1*(\2)+¶(1+)$
#$#1$*1¶$2
#

オンラインでお試しください!説明:

.+
$*

引数を単項に変換します。

+r`1*(\2)+¶(1+)$
#$#1$*1¶$2

2番目の引数が最初の引数を分割する場合は、最初の引数を#整数の結果に置き換え、残りを破棄します。最初の引数が2番目の引数より小さくなるまでこれを繰り返します。

#

ループが実行された回数をカウントします。


3

Japt、8バイト

@<Vp°X}a

それを試してみてください


これは本当にすてきです、私はまだJaptの関数メソッドの良い使用を見ていません、これは良い例です。
-Nit

@Nit、それらを理解するのにかなりの時間がかかりました-ごく最近の使用法を考え始めましたF.g()-それらは信じられないほど便利です。
シャギー




3

R、25バイト

function(p,n)log(p,n)%/%1

オンラインでお試しください!

ログ取りPベースにNしてと整数除算を行う1ことがより短いだとして、floor()。これは数値の精度に少し苦しむので、以下の答えも提示しますが、整数のオーバーフローを除き、そうすべきではありません。

R, 31 bytes

function(p,n)(x=p:0)[n^x<=p][1]

Try it online!


1
I don't know how strict the challenge requires us to be on rounding error but for example, f(243,3) is equal to 4 when it probably is required to be 5.
JDL

@JDL that's a fair point; I believe a perfectly precise answer would be ~31 bytes.
Giuseppe

1
I think you can replace p by p+.1 in the 25 byte answer and you will still be okay, for 28 bytes
JDL

Another 28 byte solution without numerical precision issues.
Robin Ryder


2

Ruby, 31 bytes

OK, so all those log-based approaches are prone to rounding errors, so here is another method that works with integers and is free of those issues:

->n,p{(0..n).find{|i|p**i>n}-1}

Try it online!

But going back to logarithms, although it is unclear up to what precision we must support the input, but I think this little trick would solve the rounding problem for all more or less "realistic" numbers:

Ruby, 29 bytes

->n,p{Math.log(n+0.1,p).to_i}

Try it online!





2

05AB1E, 6 bytes

Lm¹›_O

Try it online!


this just seems unfair to everyone else
Floris

1
@Floris Competitions are between submissions in each language not between languages right?
user202729

@user202729 yes and no. In my mind, in the end, "shortest code wins". But I noticed there was a 2-byte solution further down... These golf languages blow my mind.
Floris

1
@Floris "Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language."
user202729

1
@Floris Also... even Excel can do it in 2 builtins. Golfing languages can do this in 2 built-in too, just the builtin names are shorter. Nothing to surprise.
user202729


2

Pari/GP, 6 bytes

logint

(built-in added in version 2.7, Mar 2014. Takes two arguments, with an optional third reference which, if present, is set to the base raised to the result)


@StewieGriffin logint(x,y) from both Pari/GP and Perl/ntheory give the correct results for the 7 examples currently shown, including '3' for 1000,10.
DanaJ

+1, but I would count this as 6 bytes.
Charles

2
You're not allowed to use hardcoded inputs, so this must be a function (eg. as a lambda or definition). However you can just use logint which is valid and counts 5 bytes less.
ბიმო





1

Wolfram Language (Mathematica) 15 10 Bytes

Floor@*Log 

(requires reversed order on input)

Original submission

⌊#2~Log~#⌋&

⌊Log@##⌋& is one byte shorter
Lukas Lang

@Mathe172, that's one character shorter, but I count 13 bytes on that. The left floor and right floor count as 3 bytes each in UTF-8.
Kelly Lowder

@StewieGriffin %[10,1000] gives 3. The inputs are treated as integers rather than machine numbers unless you put a decimal place after them.
Kelly Lowder

1

Forth (gforth), 35 bytes

: f swap s>f flog s>f flog f/ f>s ;

Try it online!

Could save 5 bytes by swapping expected input parameters, but question specifies N must be first (an argument could be made that in a postfix language "First" means top-of-stack, but I'll stick to the letter of the rules for now)

Explanation

swap       \ swap the parameters to put N on top of the stack
s>f flog   \ move N to the floating-point stack and take the log(10) of N
s>f flog   \ move P to the floating-point stack and take the log(10) of P
f/         \ divide log10(N) by log10(P)
f>s        \ move the result back to the main (integer) stack, truncating in the process

1

Pyth, 6 4 bytes

s.lF

Saved 2 bytes thanks to Mmenomic
Try it online

How it works

.l is logB(A)
To be honest, I have no idea how F works. But if it works, it works.
s truncates a float to an int to give us the highest integer for M.


2
1000,10 as inputs gives 2 as output
Stewie Griffin

Another similar solution is /FlM
RK.

1

Wonder, 9 bytes

|_.sS log

Example usage:

(|_.sS log)[1000 10]

Explanation

Verbose version:

floor . sS log

This is written pointfree style. sS passes list items as arguments to a function (in this case, log).


1

Gforth, 31 Bytes

SWAP S>F FLOG S>F FLOG F/ F>S .

Usage

242 3 SWAP S>F FLOG S>F FLOG F/ F>S . 4 OK

Try it online!

Explanation

Unfortunately FORTH uses a dedicated floating-point-stack. For that i have to SWAP (exchange) the input values so they get to the floating point stack in the right order. I also have to move the values to that stack with S>F. When moving the floating-point result back to integer (F>S) I have the benefit to get the truncation for free.

Shorter version

Stretching the requirements and provide the input in float-format and the right order, there is a shorter version with 24 bytes.

FLOG FSWAP FLOG F/ F>S .
3e0 242e0 FLOG FSWAP FLOG F/ F>S . 4 OK

Try it online!


Generally for CodeGolf answers, snippets are disallowed (unless otherwise indicated in the challenge). This answer should either be wrapped with a function (Word in Forth) : f .... ; or a converted to a program that takes input using KEY or ACCEPT
reffu

@reffu What is a snippet? In my opinion a smal code part to show something, which, however, does nothing meaningful for itself. On the other hand, the code that I've provided does work without changes on "Try it online!". Should we go meta?
Kitana

In this particular case the code you posted will in fact throw a stack underflow unless you place the parameters before it. Code golf answers should generally be a self-contained program or function that produces the expected result if called later. If you follow the link to the meta post in my previous comment it explicitly mentions that the standard is for answers to be a program or a function, of which yours is neither. To fix it would only require another 4 bytes
reffu



弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.