# 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 Commented Nov 14, 2016 at 22:41
• Test case: 2103869 -> True. This (or a larger one) is necessary to test a language with a long datatype. Commented Nov 14, 2016 at 22:43
• Too bad the max is too big for language without a 64 bit integer type. Commented Nov 15, 2016 at 7:32
• I think you should be explicit about the base... in binary it's kinda half the fun :-D Commented Nov 15, 2016 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. Commented Nov 17, 2016 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=arg[1]print(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);
}
}
}

• Some other C# golfing exercises do not have using System.Linq. I'd like to discuss its requirement. For example: codegolf.stackexchange.com/a/84789/62301 Commented Nov 18, 2016 at 17:45

# Factor, 32 bytes

[ dup 3 ^ [ present ] bi@ set= ]


Try it online!

• dup Make a copy of the input.

Stack (e.g.): 100 100

• 3 ^ Cube.

Stack: 100 1000000

• [ present ] bi@ Convert them both to strings.

Stack: "100" "1000000"

• set= Are they equal when viewed as sets?

Stack: t

# Vyxal, 3 bytes

3e⊍


Try it Online!

An empty set is truthy and a set with items is falsey. If that ain't an acceptable format for output:

## 4 bytes

3e⊍¬


Try it Online!

## Explained

3e⊍
3e  # input ^ 3
⊍ # symmetric set difference between the above and input
# ¬ will negate that result, making it either 0 or 1


## Pyke, 10 bytes

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 Commented Nov 14, 2016 at 22:19
• srry you need a  instead of the z Commented Nov 14, 2016 at 22:20
• still get 10 tho Commented Nov 14, 2016 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. Commented Nov 14, 2016 at 22:28
• to the third power, you can overflow the repr Commented Nov 14, 2016 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. Commented Nov 15, 2016 at 9:30
• That is true, will fix it now, thanks ! Commented Nov 15, 2016 at 10:07
• n*n*n can be written n**3 Commented Nov 17, 2016 at 21:53
• @hoosierEE, no, not in ES6, unfortunately Commented Nov 17, 2016 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?
– user45941
Commented Nov 15, 2016 at 11:08
• yes I'm new to code golf Commented Nov 15, 2016 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 =? Commented Nov 15, 2016 at 17:31
• thanks @Oliver, how do I count the bytes? Commented Nov 15, 2016 at 17:32
• I used this site. Commented Nov 15, 2016 at 17:33
• Are you missing an using to generic namespace? Commented Nov 16, 2016 at 5:49
• @LinkNg what exactly are the requirements, I tried to find it on the website but couldn't. Commented Nov 16, 2016 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:

l            Read input
: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! Commented Nov 16, 2016 at 16:04

# Convex, 6 bytes

3#sê^!


Try it online!

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

# 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/… Commented Nov 16, 2016 at 4:43
• So, then i have to add 2 more bytes. :-/ Commented Nov 16, 2016 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. Commented Nov 16, 2016 at 13:58
• does not work for 106239 Commented Nov 16, 2016 at 16:05
• @Ipor 106239 still returns 1, 106239^3= 1199090390129919 (note the lack of "6") Commented Nov 16, 2016 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)]==[] Commented Nov 17, 2016 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. Commented Nov 17, 2016 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.

d[O~1r:ad0<f]dsfx+3^[O~1r:bd0<f]dsfxsaO[1-ddd;ar;b-d*la+sad0<m]dsmxla


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

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[0])|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. Commented Nov 19, 2016 at 18:54

## 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. Commented Mar 6, 2018 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). Commented Mar 4, 2019 at 7:59

# Pari/GP, 35 bytes

n->(d=i->Set(digits(i)))(n)==d(n^3)


Try it online!

# Husk, 9 bytes

¤=ȯOud¹^3


Try it online!

# Japt-!, 4 bytes

³skU


Try it here

³skU     :Implicit input of integer U
³        :Cubed
s       :Convert to string
kU     :Remove all digits that appear in U
:Convert to integer, resulting in NaN if all digits were removed
:Implicit output of negation of result

• What does the ! Flag do? Commented Oct 6, 2020 at 17:07
• Negates the output, @Razetime. Commented Oct 6, 2020 at 17:24
• This fails for 106239. Commented Jan 5, 2021 at 21:30

# MathGolf, 9 7 bytes

ⁿαÉ▒▀z=


Try it online!

-2 bytes thanks to KevinCruijssen. By changing the map to a for loop, we save one byte from not having to do a map (m), and another byte from not having to dump the array onto the stack (~).

## Explanation

ⁿ         pop a : push(a*a*a)
α        wrap last two elements in array
É       start block of length 3
▒      split to list of chars/digits
▀     unique elements of string/list
z    reverse sort(array)
=   pop(a, b), push(a==b)

• Ah, hadn't noticed there was already a MathGolf answer. I've deleted mine again. You can golf 2 bytes with ⁿαÉ▒▀z=. Commented Oct 7, 2020 at 9:45
– maxb
Commented Oct 7, 2020 at 13:55

# GolfScript, 6 bytes

.~3?^!


Try it online!

.        # Copy the input                "102343" "102343"
~       # Parse it to an integer        "102343" 102343
3?     # Cube it                       "102343" 1071949756947607
^    # Get the different digits      "237956"
!   # Is it an empty string?        0


# Pushy, 13 10 bytes

V3esuFsux#


Try it online!

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)


# Thunno 2, 2 bytes

³ḍ


Try it online!

Output with inverted booleans - add the ! flag to take the logical NOT of the result.

#### Explanation

    # Implicit input
³   # Cube it
ḍ  # Symmetric set difference
# Implicit output


# 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. Commented Nov 14, 2016 at 22:41