Do n and n^3 have the same set of digits?

Given a number n (0 <= n <= 2642245), check if n and n3 have the same set of digits, and output a truthy or falsey value accordingly.

For example, let's check the number 100.

1003 is 1000000.

The set of digits in 100 is {0, 1}.

The set of digits in 1000000 is {0, 1}.

Therefore, 100 should give a truthy value.

Test cases

0 -> True
1 -> True
10 -> True
107624 -> True
251894 -> True
251895 -> False
102343 -> False

Remember, this is , so the code with the fewest bytes wins.

OEIS A029795

• Proposed test case: 106239 – Dennis Nov 14 '16 at 22:41
• Test case: 2103869 -> True. This (or a larger one) is necessary to test a language with a long datatype. – mbomb007 Nov 14 '16 at 22:43
• Too bad the max is too big for language without a 64 bit integer type. – edc65 Nov 15 '16 at 7:32
• I think you should be explicit about the base... in binary it's kinda half the fun :-D – The Vee Nov 15 '16 at 13:06
• @ZoltánSchmidt 106239 is the smallest positive integer n such that 1199090390129919 – does not contain all digits of n. Some answers were only checking if n contained all digits of and thus got the wrong result for 106239. – Dennis Nov 17 '16 at 23:28

Lua, 55 bytes

Takes input on the command line. Makes n into a character class and tests the string n ^ 3 against it.

a=argprint(not("%u"):format(a^3):find("[^"..a.."]"))

Factor, 37 bytes

[ dup 3 ^ [ 10 >base unique ] bi@ = ]

(passing) Tests:

: func ( x -- ? ) dup 3 ^ [ number>string unique ] bi@ = ;
{ t } [ 0 func ] unit-test
{ t } [ 1 func ] unit-test
{ t } [ 10 func ] unit-test
{ t } [ 107624 func ] unit-test
{ t } [ 251894 func ] unit-test
{ f } [ 251895 func ] unit-test
{ f } [ 102343 func ] unit-test

C#, 86 characters

using System.Linq;i=>(i*i*i+"").All((i+"").Contains)&&(i+"").All((i*i*i+"").Contains);

Because it is a lambda, in practical use, you will need to assign it to type Func<decimal, bool>. This should, according to MSDN, be useful until you go beyond 28 digits on the i*i*i calculation. If you use the BigInteger package, you can theoretically go to however many digits you have memory for. Just substitute BigInteger for decimal. The function itself does not change.

nUnit Test:

using System;
using System.Linq;
using NUnit.Framework;

namespace CodeGolf
{
[TestFixture]
public class CodeGolfTestFixture
{
[TestCase(0, true)]
[TestCase(1, true)]
[TestCase(10, true)]
[TestCase(107624, true)]
[TestCase(251894, true)]
[TestCase(251895, false)]
[TestCase(102343, false)]
[TestCase(106239, false)]
[TestCase(2103869, true)]
public void Test(int inp, bool expectedResult)
{
Func<decimal, bool> subject = i =>
(i*i*i + "").All((i + "").Contains) &&
(i + "").All((i*i*i + "").Contains);
var observedResult = subject(inp);
Assert.AreEqual(expectedResult, observedResult);
}
}
}

3^}SR}Sq

Try it here!

Pyth, 11 10 bytes

It was difficult for me to find a function to convert to a string while searching the online tutorial. I just guessed  and was right. I suppose this site is better for searching.

q.{^Q3.{

Try it online

Explanation

Q          evaluated input (implicit Q at the end as well)
^  3        cubed
     str() - it's actually repr, but doesn't have an 'L' at the end of longs
.{     .{      convert each string to set()
q               check if equal
implicit print
• vz is Q and you can remove the last z – Maltysen Nov 14 '16 at 22:19
• srry you need a  instead of the z – Maltysen Nov 14 '16 at 22:20
• still get 10 tho – Maltysen Nov 14 '16 at 22:20
• also the tutorial is super out of date, I would recommend using the table at pyth.herokuapp.com which is always current. – Maltysen Nov 14 '16 at 22:28
• to the third power, you can overflow the repr – njzk2 Nov 14 '16 at 22:41

Batch, 202

@set/an=%1,c=n*n*n,e=1
@for /l %%a in (0,1,9)do @call:l %%a
@exit/b%e%
:l
@set f=1
@call set s=%%n:%1=%%
@if "%s%"=="%n%" set/af=1-f
@call set s=%%c:%1=%%
@if "%s%"=="%c%" set/af=1-f
@set/ae*=f

Note: Only works up to 1290 due to the limited range of Batch's data type. Takes input on the command line and returns an error level of 1 if the cube uses the same set of digits, 0 otherwise. Works by looping through each digit, checking to see whether an even number of the two strings contains the digit.

DASH, 33 bytes

@=(f\ss[sort I;unq;str])#0f ^#0 3

Usage:

(@=(f\ss[sort I;unq;str])#0f ^#0 3)500

Explanation

@
=                       #. check if the following are equal
(f\                   #. store the following to f:
ss[sort I;unq;str]  #. composition of to string, unique, sort
)
#0                  #. apply f to the arg
f ^ #0 3              #. apply f to arg cubed

ES6 (Javascript), 32, 58 bytes

Golfed

n=>(x=(a,b)=>!RegExp([^${a}]).test(b))(m=n*n*n,n)&x(n,m) Test N=n=>(x=(a,b)=>!RegExp([^${a}]).test(b))(m=n*n*n,n)&x(n,m)

N(0)
1 (true)

N(1)
1 (true)

N(10)
1 (true)

N(107624)
1 (true)

N(251894)
1 (true)

N(251895)
0 (false)

N(102343)
0 (false)

N(106239)
0 (false)
• You need to check set equality, not just subset - see Dennis' comment on the main post for the test case 106239. – Sp3000 Nov 15 '16 at 9:30
• That is true, will fix it now, thanks ! – zeppelin Nov 15 '16 at 10:07
• n*n*n can be written n**3 – hoosierEE Nov 17 '16 at 21:53
• @hoosierEE, no, not in ES6, unfortunately – zeppelin Nov 17 '16 at 22:12

Scala, 57 chars

def n(x:BigInt)=x.toString.toSet==(x*x*x).toString.toSet
• I'm not fluent in Scala, but shouldn't it be possible to remove the whitespace around the various =s? – Mego Nov 15 '16 at 11:08
• yes I'm new to code golf – Amir Asaad Nov 15 '16 at 11:13

C#, 87 bytes

Inspired by @Yodle, but I can't put a comment on his answer because I lack the reputation, I just parsed the string in a separate variable, this saves 5 characters:

var n=long.Parse(i);return new HashSet<char>(i).SetEquals(new HashSet<char>(n*n*n+""));
• Can you strip the spaces around =? – Oliver Ni Nov 15 '16 at 17:31
• thanks @Oliver, how do I count the bytes? – Flavius Nov 15 '16 at 17:32
• I used this site. – Oliver Ni Nov 15 '16 at 17:33
• Are you missing an using to generic namespace? – Link Ng Nov 16 '16 at 5:49
• @LinkNg what exactly are the requirements, I tried to find it on the website but couldn't. – Flavius Nov 16 '16 at 12:10

CJam, 15 bytes

I know it's not the best answer, but it is my first one:

l:Fi3#s$L|FL|$=

Explanation:

:F          Put it in the var F
i          Convert to int
3#        Raise to the 3rd power
s        Back to a string
$Sort L| Remove dupes FL| Remove dupes from the original input$    Sort
=   Check if they are equal
• Welcome to PPCG! – AdmBorkBork Nov 16 '16 at 16:04

Convex, 6 bytes

3#sê^!

Try it online!

Well, I guess major bugs in some operators can help in golfing sometimes...

Actually, 10 bytes

This answer uses the direct approach, using str(), sort(), uniq() on n then n**3 directly. Golfing suggestions welcome! Try it online!

$S╔3ßⁿ$S╔=

Ungolfing

Implicit input n.
$S╔ str(), sort(), uniq() on n. 3ßⁿ Push n**3.$S╔   str(), sort(), uniq() on n**3.
=     Check if the results are equal.
Implicit return.

MKSH (BASH) ,3̶9̶ 4̶1̶ 3̶6̶ 5̶2̶ 46 bytes

(38 bytes without printing return value)

3g.sh:

c=bc<<<$1^3;[${c//[$1]}${1//[$c]} ];echo$?

Usage from file:

$mksh 3g.sh 100 1$ mksh 3g.sh 11
0
$mksh 3g.sh 251894 1 Or from command line displaying return value outside (38 bytes):$ mksh -c 'c=bc<<<$0^3;[${c//[$0]}${0//[$c]} ]' 2103869;echo$?
1
$mksh -c 'c=bc<<<$0^3;[ ${c//[$0]}${0//[$c]} ]' 102343;echo $? 0$ mksh -c 'c=bc<<<$0^3;[${c//[$0]}${0//[$c]} ]' 106239;echo$?
0

My question: is my 2nd oneliner a valid solution? The result should be printed on terminal or is it enough in an invisible return value? ( I'm new to codegolf. )

• Welcome to PPCG! You don't get to define what is true and false. Generally, 1 is true, and 0 is false. meta.codegolf.stackexchange.com/questions/2190/… – mbomb007 Nov 16 '16 at 4:43
• So, then i have to add 2 more bytes. :-/ – Ipor Sircer Nov 16 '16 at 4:53
• @mbomb007 But this is Bash. Bash defines 0 as truthy and everything else as falsy. And the meta question you link seems to agree with me: truthy and falsy should be understood relative to the language. – Grimy Nov 16 '16 at 13:58
• does not work for 106239 – zeppelin Nov 16 '16 at 16:05
• @Ipor 106239 still returns 1, 106239^3= 1199090390129919 (note the lack of "6") – zeppelin Nov 16 '16 at 22:02

Python 3, 61 Bytes

n=input()
print([i for i in str(int(n)**3)if i not in n]==[])

Or in python 2 (60 Bytes):

n=input()
print[i for i in str(n**3) if i not in str(n)]==[]
• This would be shorter as a lambda: lambda n:[i for i in str(n**3) if i not in str(n)]==[] – Oliver Ni Nov 17 '16 at 15:10
• @Oliver I haven't used lambda much before, so I don't know much about how to use it. However, I will bear this in mind if I need it for a future challenge. – sonrad10 Nov 17 '16 at 20:45

Python 2, 36 33 bytes

lambda x:set(x)==set(str(x**3))

Can't use backticks (repr) on large numbers because it includes the 'L'.

dc, 69 bytes

This takes input from top of stack, and leaves a result on top of stack. The result is the count of symmetric difference between the digit sets, so zero indicates true, and other numbers indicate false.

Explanation

Expanded version as commented full program with I/O to standard streams:

#!/usr/bin/dc

?

# store 1 in a[i] for each digit i
d[O~
1r:a
d0<f]dsfx
# cube the original number
+3^
# record its digits in b[]
[O~
1r:b
d0<f]dsfx

# 0 left on stack used to initialize accumulator
sa
# for i in 9..0, add (b[i]-a[i])^2
# accumulate in register 'a'
O[1-d
dd;ar;b-d*
la+sa
d0<m]dsmx

# load result from accumulator
la

# print output
p

I hoped I could re-use the first function to store to both a[] and b[] but I couldn't find an easy way to do it. Arrays can't be pushed or popped, and it was too hard to add an indirection to the function.

Test results

Here's the test cases from the question, plus those suggested in comments:

0 -> 0
1 -> 0
10 -> 0
107624 -> 0
251894 -> 0
251895 -> 4
102343 -> 6
106239 -> 1
2103869 -> 0

And here's the first 50 terms of A029795, of 536 that I identified with this program by testing the numbers up to ten million:

0
1
10
100
1000
10000
100000
107624
109573
132485
138624
159406
165640
192574
205738
215806
251894
281536
318725
419375
427863
568314
642510
713960
953867
954086
963218
965760
1000000
1008529
1023479
1023674
1026258
1028537
1028565
1028756
1032284
1035743
1037689
1039725
1045573
1046783
1062851
1062854
1063279
1063724
1066254
1072399
1073824
1076240

PowerShell 3+, 72

filter f{"$("$_"[0..99]|sort -u)"}(($a=[long]$args)|f)-eq($a*$a*$a|f) Pretty much the same solution idea as TimmyD had, just a lot shorter (and arrived at independently). I also think there aren't that many more obvious PowerShell solutions to this. • You should specify that this is v3+ for the -Unique parameter on the Sort-Object. Otherwise, nice tricks. – AdmBorkBork Nov 19 '16 at 18:54 Pushy, 13 10 bytes V3esuFsux# Try it online! (non-competing as the language postdates the challenge) Like most other answers here, it just generates sets for both numbers and checks for equality: \ Implicit: Input on stack 1 V \ Copy into stack 2 3e \ Cube (stack 1) su \ Split into digits and create sorted set Fsu \ ^ Do the same to the second stack (not cubed) x# \ Check cross-stack equality and output (0 or 1) Mathematica 31 Bytes (f=Sign@*DigitCount)@#==f[#^3]& because Sign<Union and DigitCount<IntegerDigits Pyt, 8 bytes Đ³ąỤ⇹ąỤ\ Try it online! Outputs an empty list if true Đ³ąỤ⇹ąỤ\ Implicit input Đ Duplicate input ³ Cube ą Make array of digits Ụ Filter so you have no duplicates ⇹ swap ąỤ make array of digits and filter duplicates \ set difference • This fails for 106239. – mudkip201 Mar 6 '18 at 17:34 Brachylog, 9 7 bytes d.&^₃dp Try it online! -2 bytes thanks to Fatalize for fixing the interaction between zero and p. The predicate succeeds if the input has the same set of digits as its cube, and fails otherwise. If run as a standalone program, success prints true. and failure prints false. d The input with duplicates removed . is the output variable &^₃ and the input cubed d with duplicates removed p is a permutation of the output variable. • The interaction between 0 and p has been fixed in the latest commit. The 7 bytes d.&^₃dp should now work properly (once the commit is pulled on TIO). – Fatalize Mar 4 at 7:59 Pyth - 9 bytes Hopefully can take another char off. @I.{^Q3 ! Negation, tells if set is empty - Setwise subtraction ^Q3 String repr of input^3  String repr of implicit input • This fails for input 106239. – Dennis Nov 14 '16 at 22:41 PHP, 48 bytes <?=($f=count_chars)($a=$argv,3)==$f($a**3,3);

It's the first time I've assigned a function to a variable like this and I'm honestly quite surprised that it works.

• It works in PHP 7, yes, not in PHP 5. Also, this throws a notice because count_chars should be in apostrophes or double quotes. 3v4l.org/UsWn4 – chx Nov 18 '16 at 6:49
• @chx I know, what I was really surprised about was being able to do it in line. As for the notice, ignoring notices is standard practise in PPCG and learning what strings you can use without the quotes is a decent start for golfing PHP. – user59178 Nov 18 '16 at 9:17
• 45 +1 bytes with -F flag and $argn instead of$argv – Titus Mar 6 at 3:22

Actually, 12 bytes

3ßⁿk$╔SMi= Try it online! Explanation: 3ßⁿk$╔SMi=
3ßⁿ           copy of input, cubed
k          [input, input**3]
$╔SM for each:$          stringify
╔         remove duplicate elements
S        sort
i=  flatten and compare equality

J, 18 bytes

-:&(/:~)&~.&":^&3x

I think this is the most&s I've used in an answer to date. This is a fork:

-:&(/:~)&~.&": ^&3x

The verb on the right, ^&3x, raises the argument to the 3rd power, converting to an extended number if necessary. Then, the verb on the left takes right arg (cubed arg) and left arg (arg). & applies the verb following to each argument, then passes each argument to the preceding function. So, this is:

-:&(/:~)&~.&":
":  string representation
~.     unique elements
(/:~)        sorted
-:              are the same

Test cases

f=:-:&(/:~)&~.&":^&3x
(,. f"0) 0 1 10 107624 251894 251895 102343
0 1
1 1
10 1
107624 1
251894 1
251895 0
102343 0
f 251894
1
f 251895
0
• Holy... this was the best I could do: (]([=(~.@,)&.":)[:x:3^~]) (25 bytes, or 23 if you don't count the parens) – hoosierEE Nov 17 '16 at 21:50

C#6, 117118 115 bytes

using System.Linq;bool A(ulong n){string s=n+"",t=n*n*n+"";return s.All(x=>t.Contains(x))&t.All(x=>s.Contains(x));}

Praise System.Linq.Enumerable

+1 byte due to long range problem
-3 bytes by storing strings to variable

Ungolfed + explanations

bool A(ulong n)
{
// Convert n and n^3 to strings
string s=n+"",t=n*n*n+"";
// Two sets are equal iff:
// Foreach element in one set, it is also present in another set
return s.All(x=>t.Contains(x))&t.All(x=>s.Contains(x));
}

Julia, 34 bytes

!n=symdiff("\$n",dec(big(n)^3))==[]

How does it work? Well, strings act like arrays in many ways, so we can apply the symdiff (symmetric difference) function to a pair of strings to get an array of all characters found in only one of the two strings. If that is an empty array ([]), then the set of digits is the same.

big is used to make sure it handles larger values of n^3 (anything that would overflow in 64 bit), although it will still be limited in terms of n itself (but easily covers the range required).

C#

Without any 32 or 64 bit limits...

Func<BigInteger,bool> x = n => !(n * n * n + "").Except(n + "").Any();
• You can drop the function name and type signature - unnamed lambdas are acceptable. Additionally, you have a lot of whitespace that can be removed. Remember, in code golf, you're trying to make your code as short as possible. – Mego Nov 16 '16 at 19:16
• Thanks @Mego, I saw this question at Hot Network Questions But I think I have to read some docs before posting next answer... – L.B Nov 16 '16 at 19:28

Julia 40 bytes

h(x)= ==(Set.(digits.([x,big(x)^3]))...)

Test:

h.([0,1,10,107624,251894,251895,102343,106239,2103869])
9-element Array{Bool,1}:
true
true
true
true
true
false
false
false
true
• big(x) requires few bytes than Int128(x) – Glen O Nov 16 '16 at 6:21
• thanks, i forgot big was availble as a function (rather than just as a string macro) – Lyndon White Nov 17 '16 at 0:56