Find the super palindromes!

23

2

Consider the number 99999999. That number is obviously a palindrome. The largest prime factor of 99999999 is 137. If you divide 99999999 by 137, you get 729927. This number is also a palindrome.

The largest prime factor of 729927 is 101. 729927/101=7227 which again is a palindrome.

The largest prime factor of 7227 is 73. 7227/73=99 which again is a palindrome.

By further dividing by the largest prime factor, you get 9, 3 and finally 1, which, being one-digit numbers, are also palindromes. Since 1 has no prime factors, the procedure ends here.

Now generalizing this observation, I define a super-palindrome as a palindrome which is either 1, or which gives another super-palindrome if divided by its largest prime factor.

Credits: https://math.stackexchange.com/questions/200835/are-there-infinitely-many-super-palindromes

Given a number N, determine if it is a super palindrome or not, and print a truthy or falsey value accordingly.

Your program should print a truthy value for these inputs:

1
101
121
282
313
353
373
393
474
737
919
959
1331
1441
2882
6446
7887
8668
9559
9779

Your program should print a falsey value for these inputs:

323
432
555
583
585
646
642
696
777
969
989
2112
3553
4554
5242
5225
5445
8080
8118
9988

Remember, this is , so the code with the shortest amount of bytes wins.

Oliver Ni

Posted 2016-10-23T05:04:41.897

Reputation: 9 650

3Will the input N always be a palindrome to start with? – Sherlock9 – 2016-10-23T06:31:01.353

@Sherlock9 No.. – Oliver Ni – 2016-10-23T15:00:23.910

2Then can you please add non-palindromes to the falsey test cases? It would clarify the specification. – Sherlock9 – 2016-10-23T15:13:56.023

Answers

8

Jelly, 13 12 9 8 bytes

Æf×\D⁼U$

Try it online! or verify all test cases.

How it works

Æf×\D⁼U$  Main link. Argument: n

Æf        Yield all prime factors of n, with multiplicities and in ascending order.
  ×\      Take the cumulative product.
    D     Decimal; convert each product into the array of its base 10 digits.
       $  Combine the two links to the left into a monadic chain.
      U     Upend; reverse all arrays of decimal digits.
     ⁼      Test for equality.

Dennis

Posted 2016-10-23T05:04:41.897

Reputation: 196 637

6

Mathematica, 64 bytes

And@@PalindromeQ/@FixedPointList[#/FactorInteger[#][[-1,1]]&,#]&

Unnamed function, returning True or False. Forms a list by starting at the input, then iterating the function "me divided by my largest prime factor" until the output doesn't change. (Fortunately, Mathematica now thinks the largest prime factor of 1 is 1.) Then tests whether the list entries are palindromes (yay built-ins! boo function name length!) and Ands them all together.

Greg Martin

Posted 2016-10-23T05:04:41.897

Reputation: 13 940

Neat trick (ab)using FactorInteger[1]'s oddities with FixedPoint – LegionMammal978 – 2016-10-23T10:37:25.600

yeah, for once it helped! :) – Greg Martin – 2016-10-23T19:15:02.577

6

Mathematica, 51 bytes

#<2||PalindromeQ@#&&#0[#/FactorInteger[#][[-1,1]]]&

Recursive anonymous function. Takes a number as input and returns True or False as output.

LegionMammal978

Posted 2016-10-23T05:04:41.897

Reputation: 15 731

6

05AB1E, 9 8 bytes

Saved a byte thanks to Adnan.

Ò.pPDíïQ

Try it online!

Explanation

n = 7227 used as example

Ò           # prime factors with duplicates
            # STACK: [3, 3, 11, 73]
 .p         # prefixes
            # STACK: [[3], [3, 3], [3, 3, 11], [3, 3, 11, 73]]
   P        # product
            # STACK: [3, 9, 99, 7227]
    D       # duplicate
            # STACK: [3, 9, 99, 7227], [3, 9, 99, 7227]
     í      # reverse each
            # STACK: [3, 9, 99, 7227], ['3', '9', '99', '7227']
      ï     # convert to  int
            # STACK: [3, 9, 99, 7227], [3, 9, 99, 7227]
       Q    # check for equality
            # STACK: 1
            # implicit output

Emigna

Posted 2016-10-23T05:04:41.897

Reputation: 50 798

I think Ò.pPDíïQ also should work. – Adnan – 2016-10-23T21:38:48.127

5

Pyth - 15 12 bytes

Beat Jelly :P :/

Unfortunately, all those implicit maps do not get shorter when combined into an explicit one since the last one is an auto-splat.

.A_IM`M*M._P

Test Suite.

Gets all the prefixes of the prime factorization, the products of which will be the intermediate super palindromes, and checks if all of them are palindromes.

Maltysen

Posted 2016-10-23T05:04:41.897

Reputation: 25 023

4

Mathematica, 71 63 bytes

And@@PalindromeQ/@FoldList[1##&,Join@@Table@@@FactorInteger@#]&

Explanation

FactorInteger@#

Factor the input. (e.g. 8668 -> {{2, 2}, {11, 1}, {197, 1}}; for each list in the output, the first element is the prime factor, and the second one is the power.

Join@@Table@@ ...

For each factor-power pair, duplicate the first element by the second element, and flatten the entire thing. ({{2, 2}, {11, 1}, {197, 1}} -> {{2, 2}, {11}, {197}} -> {2, 2, 11, 197})

FoldList[1##&, ... ]

Iterate through the list, multiplying the elements. ({2, 2, 11, 197} -> {2, 2 * 2, 2 * 2 * 11, 2 * 2 * 11 * 197} -> {2, 4, 44, 8668})

And@@PalindromeQ/@ ...

Check whether all of the resulting numbers are palindromes, and apply the And operator. ({2, 4, 44, 8668} -> {True, True, True, True} -> True)

JungHwan Min

Posted 2016-10-23T05:04:41.897

Reputation: 13 290

oooo, nicely done! Now I gotta go see if I can save 2 bytes somewhere.... – Greg Martin – 2016-10-23T19:17:12.213

3

Brachylog, 14 bytes

1|r?$ph:?r/:0&

Try it online!

Explanation

This implements the formula explained in the challenge description.

Computing all products of suffixes of the prime factorization and checking that they are all palindromes is 1 byte longer (1|$p:@]f:{*.r}a).

1                  Input = 1
 |                 OR
  r?               Reversing the Input results in the Input
    $p             Get the prime factors of the Input
      h            Take the first one (the biggest)
       :?r/        Divide the Input by that prime factor
           :0&     Call this predicate recursively with that new number as input

Fatalize

Posted 2016-10-23T05:04:41.897

Reputation: 32 976

2

Racket 238 bytes

(define(p n)(=(string->number(list->string(reverse(string->list(number->string n)))))n))
(if(= n 1)#t(begin(let o((n n))(define pd(prime-divisors n))(if(null? pd)#f(begin(let((m(/ n(last pd))))
(cond[(= m 1)#t][(p m)(o m)][else #f])))))))

Ungolfed:

(define (f n)
  (define (palin? n)                      ; define palindrome of number
    (=(string->number
       (list->string
        (reverse
         (string->list
          (number->string n)))))
      n))
  (if(= n 1)#t
     (begin
       (let loop ((n n))
         (define pd (prime-divisors n))   ; find prime divisors
         (if (null? pd) #f                ; end if none- not superpalindrome
             (begin
               (let ((m (/ n (last pd)))) ; divide by largest prime divisor
                 (cond                    ; test quotient
                   [(= m 1) #t]           ; end if 1: super-palindrome found
                   [(palin? m) (loop m)]  ; loop with quotient if palindrome
                   [else #f]              ; end if not palindrome
                   ))))))))

Testing:

(f 1)
(f 101)
(f 121)
(f 282)
(f 313)
(f 353)
(f 373)
(f 393)
(f 474)
(f 737)
(f 919)
(f 959)
(f 1331)
(f 1441)
(f 2882)
(f 6446)
(f 7887)
(f 8668)
(f 9559)
(f 9779)
(f 99999999)

Output:

#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t
#t

rnso

Posted 2016-10-23T05:04:41.897

Reputation: 1 635

I'm not familiar with Racket, but is it neccessary that your helper function palin is a five bytes long name? – Roman Gräf – 2016-10-23T07:04:35.137

I had corrected it earlier but it did not paste here properly. 238 bytes is with just 'p' as the name. Thanks for pointing out. – rnso – 2016-10-23T07:14:29.097

2

J, 30 bytes

0:`(%1>.{:@q:)@.((-:|.)@":)^:_

Error for falsey, 1 for truthy.

Initial attempt, does not error for falsey, 40 bytes:

0:`(([:$:]%{:@q:)`[@.(1&=))@.((-:|.)@":)

Explanation

0:`(%1>.{:@q:)@.((-:|.)@":)^:_
                           ^:_  repeat until convergent
              @.((-:|.)@":)     if the number is palindromic:
   (         )                   do the stuff inside, which is a 4-train
        {:@q:                    largest prime factor
     1>.                         (or 1, if smaller than 1)
    %                            divide the original number by this value
0:`                             otherwise, return 0
                                (because of ^:_, this will be passed into q:, which will
                                error because 0 cannot be factored.)

Test cases

   NB. collect errors; 0 if errored, otherwise the result of the function
   NB. left arg: values; right arg: boxed name of function
   errors =: 4 : 0
    f =. y`:6
    l =: ''
    for_e. x do.
        try.
            l =. l , f e
        catch.
            l =. l , 0
        end.
    end.
    l
)
   s =: 0:`(%1>.{:@q:)@.((-:|.)@":)^:_
   t =: 1 101 121 282 313 353 373 393 474 737 919 959 1331 1441 2882 6446 7887 8668 9559 9779
   f =: 323 432 555 583 585 646 642 696 777 969 989 2112 3553 4554 5242 5225 5445 8080 8118 9988
   t ,. f
   1  323
 101  432
 121  555
 282  583
 313  585
 353  646
 373  642
 393  696
 474  777
 737  969
 919  989
 959 2112
1331 3553
1441 4554
2882 5242
6446 5225
7887 5445
8668 8080
9559 8118
9779 9988
   (t ,. f) errors"1 0 <'s'
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0
1 0

Conor O'Brien

Posted 2016-10-23T05:04:41.897

Reputation: 36 228

2

아희(Aheui), 309 bytes (100 chars * 3 bytes + 9 newlines)

방빩반룸있쁏멐솔쌀잌
앟놂숙참뿔썁썸뻙솝셜
본서번분번뮴딸냥별쀼
슉눇번낢퉅쑫썬쌀본묳
뽇서본석첫삭뽑롷떵춤
분촐럶사눙읽숟뗘분뻨
듐삭빶쏘윙잉썩손뵬괆
쌰뭉쇼텰궮변번첳웅텩
뽇흶아희쾯볻훼윺엄솝
코드골프욉쁍숙쌉삼쏩

I'm so happy that I actually finished it!

I'm new to this language, so any tip on improving byte count is welcome.

Try it here! (copy and paste the code)

Cleaner version

방빠반루ㅇ쀼머솔쌀이
아노숙차뿌썁썸뻐솝셜
본서번분번뮤따냐별쀼
슉누번나투쑫썬쌀본묘
뽀서본석처삭뽀로떠추
분초러사누이숟뗘분뻐
듀삭빠쏘ㅇ이썩손뵬ㅇ
쌰뭉쇼텨이변번처우텨
뽀희ㅇㅇㅇ볻ㅇ유어솝
ㅇㅇㅇㅇㅇㅇ숙쌉삼쏩

JungHwan Min

Posted 2016-10-23T05:04:41.897

Reputation: 13 290

What's the difference between the normal version and the clearner one? – Oliver Ni – 2016-10-25T14:57:08.560

@Oliver The first version has no NOPs (ㅇ) and has more complex characters (They are identical code; I only made the first one look more esoteric). The second version is for those who would like to actually read the program, without all the gibberish. – JungHwan Min – 2016-10-25T15:01:39.757

0

Actually, 29 bytes

There are probably several sections of this code that could be golfed, though I'm not sure where yet. Golfing suggestions welcome. Try it online!

╗1`X╜$;R=;╝╜yN╜\;╗1<&`╬X╜DY╛&

Ungolfing

          Implicit input n.
╗         Save n to register 0.
1`...`╬   Run the following function on the stack while TOS is truthy.
  X         Discard the previous truthy.
  ╜         Push n from register 0.
  $         Push str(n).
  ;R=       Check if str(n) == str(n)[::-1], i.e. if n is a palindrome.
  ;╝        Save a copy of (is n a palindrome?) to register 1.
  ╜yN       Get the largest prime factor of n.
  ╜\        Divide n by its largest prime factor.
  ;╗        Save a copy of n // l_p_f to register 0.
  1<        Check if 1 < n // l_p_f. This returns 0 only if n // l_p_f is 1.
  &         Logical AND (is n a palindrome?) and (is n // l_p_f > 1?).
            This quits if we have reached a non-palindrome or we have reached 1.
X         Discard the falsey that ended the previous function.
╜         Get the last value saved to register 0 (could be 1 or a non-palindrome // l_p_f)
DY        This returns 1 if register 0 was a 1, else 0.
╛&        Logical AND with register 1 (was the last n a palindrome?) to get our result.
          Implicit return.

Sherlock9

Posted 2016-10-23T05:04:41.897

Reputation: 11 664

0

Scala, 138 bytes

def?(n:Int):Int={val p=Stream.from(2).filter(n%_==0)(0)
if(p==n)n else?(n/p)}
def s(i:Int):Boolean=i<2||(i+"")==(i+"").reverse&&s(i/ ?(i))

Ungolfed:

def largestFactor(n:Int):Int={
  val p=Stream.from(2).filter(n%_==0).head
  if(p==n)n else largestFactor(n/p)}
def superPalindrome(i:Int):Boolean=i<2||(i+"")==(i+"").reverse&&superPalindrome(i/ largestFactor(i))

Explanation:

def?(n:Int):Int={                       //define a method for the largest prime factor
  val p=Stream.from(2).filter(n%_==0)(0)  //find the first factor of n
  if(p==n)n else?(n/p)                    //if it's n, return n else the next factor
}
def s(i:Int):Boolean=                     //method for the superprime
  i<2                                     //if s<2 return true
  ||                                      //else return:
    (i+"")==(i+"").reverse                  //is i a palindrome
    &&                                      //and
    s(i/ ?(i))                              //is i divided by it's largestPrimeFactor a superpalindrome

corvus_192

Posted 2016-10-23T05:04:41.897

Reputation: 1 889

0

JavaScript (ES6), 78 bytes

(n,d=2,p=1)=>n%d?n<2||f(n,d+1,p):[...p=p*d+''].reverse().join``==p&&f(n/d,d,p)

Recursively builds the prime factorisation prefixes and checks them for palindromicity.

Neil

Posted 2016-10-23T05:04:41.897

Reputation: 95 035

0

Java 7, 133 bytes

int c(int a){int x=a,y=0,z=a,i=2;for(;x>0;y=y*10+x%10,x/=10);for(;z>1;i++)for(;z%i<1;z/=i);if(a<2)return 1;return y!=a?0:c(a/(i-1));}

Ungolfed

    static int c( int a ){
    int x = a , y = 0 , z = a , i = 2 ;

    for ( ; x > 0 ; y = y * 10 + x % 10 , x /= 10 ) ;

    for ( ; z > 1 ; i++ )
    for ( ; z % i < 1 ; z /= i ) ; 

    if ( a < 2 )
      return 1 ;

    return y != a ? 0 : c( a / ( i - 1 ) ) ;       
 }

Numberknot

Posted 2016-10-23T05:04:41.897

Reputation: 885