Self-contained powers

Given integer n, output the smallest exponent e greater than 1 such that n^e contains n as a substring.

For example, for 25, the answer should be 2, as 25 ^ 2 = 625, which contains 25 as a substring, but the answer for 13 should be 10, as 13 ^ 10 = 137858491849, so 10 is the lowest exponent for which the result contains 13 as a substring.

Rules

• Standard I/O rules
• Standard loopholes apply
• Shortest code in bytes wins
• n will always be an integer greater than 0

Test Cases

1 => 2   (1 ^ 2 = 1)
2 => 5   (2 ^ 5 = 32)
3 => 5   (3 ^ 5 = 243)
4 => 3   (4 ^ 3 = 64)
5 => 2   (5 ^ 2 = 25)
6 => 2   (6 ^ 2 = 36)
7 => 5   (7 ^ 5 = 16807)
8 => 5   (8 ^ 5 = 32768)
9 => 3   (9 ^ 3 = 729)
10 => 2  (10 ^ 2 = 100)
11 => 11 (11 ^ 11 = 285311670611)
12 => 14 (12 ^ 14 = 1283918464548864)
13 => 10 (13 ^ 10 = 137858491849)
14 => 8  (14 ^ 8 = 1475789056)
15 => 26 (15 ^ 26 = 3787675244106352329254150390625)
16 => 6  (16 ^ 6 = 16777216)
17 => 17 (17 ^ 17 = 827240261886336764177)
18 => 5  (18 ^ 5 = 1889568)
19 => 11 (19 ^ 11 = 116490258898219)
20 => 5  (20 ^ 5 = 3200000)
25 => 2  (25 ^ 2 = 625)
30 => 5  (30 ^ 5 = 24300000)
35 => 10 (35 ^ 10 = 2758547353515625)
40 => 3  (40 ^ 3 = 64000)
45 => 5  (45 ^ 5 = 184528125)
50 => 2  (50 ^ 2 = 2500)
55 => 11 (55 ^ 11 = 13931233916552734375)
60 => 2  (60 ^ 2 = 3600)
65 => 17 (65 ^ 17 = 6599743590836592050933837890625)
70 => 5  (70 ^ 5 = 1680700000)
75 => 3  (75 ^ 3 = 421875)
80 => 5  (80 ^ 5 = 3276800000)
85 => 22 (85 ^ 22 = 2800376120856162211833149645328521728515625)
90 => 3  (90 ^ 3 = 729000)
95 => 13 (95 ^ 13 = 51334208327950511474609375)
100 => 2 (100 ^ 2 = 10000)


Python script to generate the first 1000 answers

• Related – Skidsdev Nov 28 '18 at 18:07
• A045537 – Shaggy Nov 28 '18 at 19:55

Perl 6, 31 bytes

{$^a;first {$a**$_~~/$a/},2..*}


Try it online!

R, 69 44 bytes

function(n,i=2){while(!grepl(n,n^i))i=i+1;i}


Anonymous function. Works on large i when n is converted to BigZ (see TIO). Thanks for teaching me something Giuseppe and digEmAll!

Try it online!

• 61 bytes -- you had an extra space in n, ?n^i and paste converts to character by default :-) – Giuseppe Nov 28 '18 at 19:57
• 56 bytes -- returning i should be sufficient. – Giuseppe Nov 28 '18 at 19:58
• 44 bytes paste is not necessary, grepl converts to character by default :) – digEmAll Nov 29 '18 at 7:54
• The problem is that it is "faulty" when exponents become big because of floating points accuracy and the fact that big numbers are converted to string in scientific notation. For instance 15 returns 17 while it should be 26. So, theoretically this works, but in practice we should use a Big Integer package or something like that... – digEmAll Nov 29 '18 at 8:12
• @digEmAll for BigInt you could just force input to be a bigInt like BigZ from gmp and it should still work, except possibly for converting i to a bigZ as well – Giuseppe Nov 29 '18 at 23:51

Python 2, 42 41 bytes

-1 byte thanks to Ørjan Johansen (returning y directely)

f=lambda x,y=2:y*(xinx**y)or f(x,y+1)


Try it online!

Explanation/Ungolfed

Recursive function trying from $$\2,3\dots\$$ until we succeed:

# Start recursion with y=2
def f(x,y=2):
# If we succeed, we arrived at the desired y
if x in x**y:
return y
# Else we try with next y
else:
return f(x, y+1)


Try it online!

• Returning y is shorter – Ørjan Johansen Nov 28 '18 at 21:44
• @ØrjanJohansen: Weird, I thought I tried that, not exactly sure what I missed. Thanks a lot! – ბიმო Nov 28 '18 at 22:03
• I had to swap the multiplication to avoid a space, maybe that was it? – Ørjan Johansen Nov 28 '18 at 22:26
• @ØrjanJohansen: Probably that was it, yeah. – ბიმო Nov 29 '18 at 0:04

JavaScript (ES6 / Node.js),  41  40 bytes

Saved 1 byte thanks to @Shaggy

Takes input as a Number (works for $$\n<15\$$) or a BigInt literal.

n=>(g=x=>${x*=n}.match(n)?2:-~g(x))(n)  Try it online! • Ended up with a solution very similar to yours for 40 bytes – Shaggy Nov 28 '18 at 20:13 • @Shaggy You need to use big integers, otherwise it wont return the correct answer in some test cases. At the end it has the same bytecount n=>(g=x=>${x*=n}.match(n)?2n:-~g(x))(n) – Luis felipe De jesus Munoz Nov 28 '18 at 20:17
• @LuisfelipeDejesusMunoz, generally we don't need to worry about precision issues but it will work with BigInts too. – Shaggy Nov 28 '18 at 20:19
• Minor thing but if this uses BigInt shouldn't the title be JavaScript (Node.js)? ES6 doesn't have BigInt yet. – Shieru Asakoto Nov 29 '18 at 7:53
• @ShieruAsakoto You're right. My initial intention was to explain that it works with either a Number or a BigInt. Now clarified. – Arnauld Nov 29 '18 at 8:11

APL (Dyalog Unicode), 2523 17 bytes

-2 bytes thanks to @Erik the Outgolfer

-6 bytes thanks to @ngn

thanks to @H.PWiz for making the code not require a custom ⎕pp (print precision)

⊢⍟×⍣(∨/(⍕÷)⍷0⍕⊣)⍨


Try it online!

⊢⍟×⍣(∨/(⍕÷)⍷0⍕⊣)⍨
×⍣(          )⍨ generates a geometric progression by repeatedly multiplying the argument
by its original value
∨/(⍕÷)⍷0⍕⊣   the progression stops when this function, applied between the new and the
last old member, returns true
÷        the original argument (ratio between two consecutive members)
⍕         formatted as a string
⍷      occurrences within...
0⍕    ...the formatted (with 0 digits after the decimal point)...
⊣   ...new member
∨/           are there any?
⊢⍟                use logarithm to determine what power of ⍵ we reached

• This fails for 17 because it it finds 17 in 17^14=1.6837782655940093E17, but idk to what precision answers should support – Cows quack Nov 28 '18 at 19:07
• @Cowsquack I just have to arbitrarily adjust ⎕PP I guess – Quintec Nov 28 '18 at 19:09
• Oh wait that won't even work – Quintec Nov 28 '18 at 19:10
• – Erik the Outgolfer Nov 28 '18 at 20:44
• 19 bytes – ngn Nov 28 '18 at 21:19

Pyth, 9 bytes

f}Q^QT2


Try it online!

Brachylog, 8 bytes

;.^s?∧ℕ₂


Try it online!

Explanation

;.^         Input ^ Output…
s?       …contains the Input as a substring…
∧      …and…
ℕ₂    …the Output is in [2,+∞)


05AB1E, 7 bytes

∞>.Δm¹å


Try it online!

Explanation:

∞>.Δm¹å  //full program
∞        //push infinite list, stack = [1,2,3...]
>       //increment, stack is now [2,3,4...]
.Δ     //find the first item N that satisfies the following
¹   //input
å  //is in
m    //(implicit) input **  N


SAS, 71 66 bytes

Edit: Removed ;run; at the end, since it's implied by the end of inputs.

data a;input n;e=1;do until(find(cat(n**e),cat(n)));e+1;end;cards;


Input data is entered after the cards; statement, like so:

data a;input n;e=1;do until(find(cat(n**e),cat(n)));e+1;end;cards;
1
2
3
4
5
6
7
8
9
10
11
12
13
14


Generates a dataset a containing the input n and the output e.

• This looks to be a function definition, or equivalent (I assume actually a "macro") This means that requiring it be called with arguments (ie %p(n)) is totally fine, however output depends on whether macros in SAS can return values. If they can return, the "output" should be by returning the result, otherwise it should output it by whatever standard output method is supported – Skidsdev Nov 29 '18 at 20:28
• @Skidsdev Thanks for the feedback! SAS is a bit weird; macros aren't really functions, they're just a text substitution language that generates 'real' SAS code when compiled. I had a look at how other people have done I/O for SAS in codegolf, and edited my answer based on that, getting rid of the macro statements. – Josh Eller Nov 29 '18 at 20:56

Jelly, 7 bytes

2ẇ*¥@1#


Try it online!

Clean, 99 bytes

import StdEnv,Text,Data.Integer
$n=hd[p\\p<-[fromInt 2..]|indexOf(""<+n)(""<+prod(repeatn p n))>=0]  Try it online! If it doesn't need to work for giant huge numbers, then Clean, 64 bytes import StdEnv,Text$n=hd[p\\p<-[2..]|indexOf(""<+n)(""<+n^p)>=0]


Try it online!

Java (OpenJDK 8), 84 bytes

Takes input as a String representing the number and outputs an int.

Most of the bytes come from the verbosity of the BigDecimal being needed to process the large numbers.

n->{int i=1;while(!(new java.math.BigDecimal(n).pow(++i)+"").contains(n));return i;}


Try it online!

How it works

This is fairly simple but I'll include the explanation for posterity;

n->{                                    // Lamdba taking a String and returning an int
int i=1;                            // Initialises the count
while(!                             // Loops and increments until
(new java.math.BigDecimal(n)    // Creates a new BigDecimal from the input n
.pow(++i)+"")               // Raises it to the power of the current count
.contains(n)                // If that contains the input, end the loop
);
return i;                           // Return the count
}


Ruby, 37 bytes

->n,i=2{i+=1until/#{n}/=~"#{n**i}";i}


Try it online!

Japt, 10 bytes

@pX søU}a2


Try it

JavaScript (Node.js), 45 bytes

Test cases taken from @Arnauld's answer

a=>eval("for(i=1n;!(''+a**++i).match(a););i")


Try it online!

Charcoal, 19 bytes

Ｗ∨‹Ｌυ²¬№ＩΠυθ⊞υＩθＩＬυ


Try it online! Link is to verbose version of code. Explanation:

Ｗ∨‹Ｌυ²¬№ＩΠυθ⊞


Repeat until the the list length is at least 2 and its product contains the input...

⊞υＩθ


... cast the input to integer and push it to the list.

ＩＬυ


Cast the length of the list to string and implicitly print it.

Python 3, 63 58 bytes

def f(n,e=2):
while str(n)not in str(n**e):e+=1
return e


Try it online!

Python2 would probably be shorter, but I like using 3. Coming up wiht a lambda is difficult, but I'm trying a few things.

• I dont know python but, isn't it shorter using lambda? – Luis felipe De jesus Munoz Nov 28 '18 at 20:05
• @LuisfelipeDejesusMunoz I started off trying to do that, but IDLE complained about having a bare while in a lambda. Maybe I can try some other ways.. – Gigaflop Nov 28 '18 at 20:07
• Maybe some recursive function? – Luis felipe De jesus Munoz Nov 28 '18 at 20:10
• Defining e in the arguments-list (ie. def f(n,e=2)) and n**e should save some bytes, Python 2 would indeed save quite some bytes. – ბიმო Nov 28 '18 at 20:38
• @LuisfelipeDejesusMunoz Lambdas are not like functions. The right hand side of a lambda has to be a single expression, and flow-control commands like for or while do not work. – DJMcMayhem Nov 28 '18 at 20:44

MathGolf, 10 bytes

ôkï⌠#k╧▼ï⌠


Try it online!

Explanation

This feels extremely wasteful, having to read the input explicitly twice, having to increment the loop counter twice.

ô            start block of length 6
ï          index of current loop, or length of last loop
⌠         increment twice
#        pop a, b : push(a**b)
╧      pop a, b, a.contains(b)
▼     do while false with pop
ï    index of current loop, or length of last loop
⌠   increment twice


Ruby, 41 bytes

f=->n,a=n{(a*=n).to_s=~/#{n}/?2:1+f[n,a]}


Try it online!

C# (.NET Core), 104 89 bytes

a=>{int i=2;while(!(System.Numerics.BigInteger.Pow(a,i)+"").Contains(a+""))i++;return i;}


Try it online!

-1 byte: changed for loop to while (thanks to Skidsdev)
-14 bytes: abused C#'s weird string handling to remove ToString() calls

Need to use C#'s BigInteger library, as the standard numeric C# types (int, double, long, ulong, etc.) fail for some larger numbers (including 12, 15, and 17).

Ungolfed:

a => {
int i = 2;                                          // initialize i

while( !(System.Numerics.BigInteger.Pow(a,i) + "")  // n = a^i, convert to string
.Contains(a + ""))      // if n doesn't contain a
i++;                                                // increment i

return i;
}

• You can save 1 byte by switching to a while loop – Skidsdev Nov 29 '18 at 13:53

Python 2, 47 bytes

i,e=input(),2
whileinot ini**e:e+=1
print e


Try it online!

Inspired by @Gigaflop's solution.

Tcl, 69 81 bytes

proc S n {incr i
while {![regexp $n [expr$n**[incr i]]]} {}
puts $i}  Try it online! PowerShell(V3+), 67 bytes function f{param($n)$i=1;do{}until([math]::pow($n,++$i)-match$n)\$i}


Common Lisp, 78 bytes

(lambda(n)(do((e 2(1+ e)))((search(format()"~d"n)(format()"~d"(expt n e)))e)))


Try it online!

J, 26 bytes

2>:@]^:(0=[+/@E.&":^)^:_~]


Try it online!

NOTE: I've changed the final ] to x: in the TIO, to make the tests pass for larger integers.

Oracle SQL, 68 bytes

select max(level)+1 from dual,t connect by instr(power(x,level),x)=0


There is an assumption that source number is stored in a table t(x), e.g.

with t as (select 95 x from dual)


Test in SQL*Plus

SQL> with t as (select 95 x from dual)
2  select max(level)+1 from dual,t connect by instr(power(x,level),x)=0
3  /

MAX(LEVEL)+1
------------
13