51
\$\begingroup\$

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

\$\endgroup\$
9
  • 29
    \$\begingroup\$ Proposed test case: 106239 \$\endgroup\$
    – Dennis
    Nov 14, 2016 at 22:41
  • 9
    \$\begingroup\$ Test case: 2103869 -> True. This (or a larger one) is necessary to test a language with a long datatype. \$\endgroup\$
    – mbomb007
    Nov 14, 2016 at 22:43
  • 6
    \$\begingroup\$ Too bad the max is too big for language without a 64 bit integer type. \$\endgroup\$
    – edc65
    Nov 15, 2016 at 7:32
  • 18
    \$\begingroup\$ I think you should be explicit about the base... in binary it's kinda half the fun :-D \$\endgroup\$
    – The Vee
    Nov 15, 2016 at 13:06
  • 10
    \$\begingroup\$ @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. \$\endgroup\$
    – Dennis
    Nov 17, 2016 at 23:28

81 Answers 81

2
\$\begingroup\$

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.."]"))
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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);
        }
    }
}
\$\endgroup\$
1
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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`
\$\endgroup\$
1
\$\begingroup\$

Pyke, 10 bytes

3^`}SR`}Sq

Try it here!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
7
  • \$\begingroup\$ vz is Q and you can remove the last z \$\endgroup\$
    – Maltysen
    Nov 14, 2016 at 22:19
  • \$\begingroup\$ srry you need a ` instead of the z \$\endgroup\$
    – Maltysen
    Nov 14, 2016 at 22:20
  • \$\begingroup\$ still get 10 tho \$\endgroup\$
    – Maltysen
    Nov 14, 2016 at 22:20
  • \$\begingroup\$ also the tutorial is super out of date, I would recommend using the table at pyth.herokuapp.com which is always current. \$\endgroup\$
    – Maltysen
    Nov 14, 2016 at 22:28
  • \$\begingroup\$ to the third power, you can overflow the repr \$\endgroup\$
    – njzk2
    Nov 14, 2016 at 22:41
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
4
  • 1
    \$\begingroup\$ You need to check set equality, not just subset - see Dennis' comment on the main post for the test case 106239. \$\endgroup\$
    – Sp3000
    Nov 15, 2016 at 9:30
  • \$\begingroup\$ That is true, will fix it now, thanks ! \$\endgroup\$
    – zeppelin
    Nov 15, 2016 at 10:07
  • \$\begingroup\$ n*n*n can be written n**3 \$\endgroup\$ Nov 17, 2016 at 21:53
  • 2
    \$\begingroup\$ @hoosierEE, no, not in ES6, unfortunately \$\endgroup\$
    – zeppelin
    Nov 17, 2016 at 22:12
1
\$\begingroup\$

Scala, 57 chars

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

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+""));
\$\endgroup\$
6
  • \$\begingroup\$ Can you strip the spaces around =? \$\endgroup\$
    – Oliver Ni
    Nov 15, 2016 at 17:31
  • \$\begingroup\$ thanks @Oliver, how do I count the bytes? \$\endgroup\$
    – Flavius
    Nov 15, 2016 at 17:32
  • \$\begingroup\$ I used this site. \$\endgroup\$
    – Oliver Ni
    Nov 15, 2016 at 17:33
  • \$\begingroup\$ Are you missing an using to generic namespace? \$\endgroup\$
    – Link Ng
    Nov 16, 2016 at 5:49
  • \$\begingroup\$ @LinkNg what exactly are the requirements, I tried to find it on the website but couldn't. \$\endgroup\$
    – Flavius
    Nov 16, 2016 at 12:10
1
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Nov 16, 2016 at 16:04
1
\$\begingroup\$

Convex, 6 bytes

3#sê^!

Try it online!

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

\$\endgroup\$
1
\$\begingroup\$

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. )

\$\endgroup\$
8
  • 1
    \$\begingroup\$ 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/… \$\endgroup\$
    – mbomb007
    Nov 16, 2016 at 4:43
  • \$\begingroup\$ So, then i have to add 2 more bytes. :-/ \$\endgroup\$ Nov 16, 2016 at 4:53
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Grimmy
    Nov 16, 2016 at 13:58
  • 1
    \$\begingroup\$ does not work for 106239 \$\endgroup\$
    – zeppelin
    Nov 16, 2016 at 16:05
  • 1
    \$\begingroup\$ @Ipor 106239 still returns 1, 106239^3= 1199090390129919 (note the lack of "6") \$\endgroup\$
    – zeppelin
    Nov 16, 2016 at 22:02
1
\$\begingroup\$

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)]==[]
\$\endgroup\$
2
  • \$\begingroup\$ This would be shorter as a lambda: lambda n:[i for i in str(n**3) if i not in str(n)]==[] \$\endgroup\$
    – Oliver Ni
    Nov 17, 2016 at 15:10
  • \$\begingroup\$ @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. \$\endgroup\$
    – AvahW
    Nov 17, 2016 at 20:45
1
\$\begingroup\$

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'.

\$\endgroup\$
1
\$\begingroup\$

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

# read input
?

# 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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ You should specify that this is v3+ for the -Unique parameter on the Sort-Object. Otherwise, nice tricks. \$\endgroup\$ Nov 19, 2016 at 18:54
1
\$\begingroup\$

Mathematica 31 Bytes

(f=Sign@*DigitCount)@#==f[#^3]&

because Sign<Union and DigitCount<IntegerDigits

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ This fails for 106239. \$\endgroup\$
    – mudkip201
    Mar 6, 2018 at 17:34
1
\$\begingroup\$

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.
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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). \$\endgroup\$
    – Fatalize
    Mar 4, 2019 at 7:59
1
\$\begingroup\$

Pari/GP, 35 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Husk, 9 bytes

¤=ȯOud¹^3

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ What does the ! Flag do? \$\endgroup\$
    – Razetime
    Oct 6, 2020 at 17:07
  • \$\begingroup\$ Negates the output, @Razetime. \$\endgroup\$
    – Shaggy
    Oct 6, 2020 at 17:24
  • \$\begingroup\$ This fails for 106239. \$\endgroup\$
    – Makonede
    Jan 5, 2021 at 21:30
1
\$\begingroup\$

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)
\$\endgroup\$
2
  • \$\begingroup\$ Ah, hadn't noticed there was already a MathGolf answer. I've deleted mine again. You can golf 2 bytes with ⁿαÉ▒▀z=. \$\endgroup\$ Oct 7, 2020 at 9:45
  • \$\begingroup\$ @KevinCruijssen Even I had forgotten about this answer, good catch! \$\endgroup\$
    – maxb
    Oct 7, 2020 at 13:55
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Pyth - 9 bytes

Hopefully can take another char off.

@I.{`^Q3`

Test Suite.

!          Negation, tells if set is empty
 -         Setwise subtraction
  `^Q3     String repr of input^3
  `        String repr of implicit input
\$\endgroup\$
1
  • 2
    \$\begingroup\$ This fails for input 106239. \$\endgroup\$
    – Dennis
    Nov 14, 2016 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.