5
\$\begingroup\$

Given a number determine if it is a circular prime.

A circular prime is a prime where if you rotate the digits you still get prime numbers. 1193 is circular prime because 1931 and 9311 and 3119 are all primes.

Input:          Output:
1193            circular
11939           circular
1456            nothing
193939          circular
1111111         nothing
7               circular
23              nothing

Shortest code wins.

\$\endgroup\$
  • 1
    \$\begingroup\$ I don't think this should have the code-challenge tag. \$\endgroup\$ – Cruncher Nov 12 '13 at 19:18
  • 1
    \$\begingroup\$ Not a big deal, but they're sort of disjoint. codegolf.stackexchange.com/tags/code-challenge/info "A code challenge is a competition for creative ways to solve a programming puzzle for an objective criterion other than code size." \$\endgroup\$ – Cruncher Nov 12 '13 at 19:36
  • 6
    \$\begingroup\$ -1 You stated: "Shortest code wins" but awarded the check to a submission that was 4 times as long as the shortest submitted! \$\endgroup\$ – DavidC Nov 14 '13 at 19:50
  • 4
    \$\begingroup\$ @DavidCarraher Some problems on this site require specific output. This is one. Deal with it and stop whining. "Oh, poor me, my output 99,98,97... is equivalent to the lyrics of '99 bottles of beer on the wall' but it wasn't an accepted answer!" \$\endgroup\$ – boothby Nov 14 '13 at 22:13
  • 4
    \$\begingroup\$ @Boothby. Bad example. "99 bottles of beer on the wall" is all about crafting a specific output, the lyrics of a song. The present example is advertised a test of circularity of a number: "Given a number determine if it is a circular prime." Example output was given. But it was not stated (nor should it have been, in my view) that that specific format is required). \$\endgroup\$ – DavidC Nov 14 '13 at 22:21

13 Answers 13

4
\$\begingroup\$

GolfScript, 47 characters

:s,,{)s/(+~:P{(.P\%}do(},!"nothing
circular"n/=

Input must be given on STDIN without trailing newline (online example).

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It's beautiful :) \$\endgroup\$ – Quillion Nov 15 '13 at 15:04
8
\$\begingroup\$

J, 47 chars (w/ formatted output)

('nothing';'circular'){~*/1&p:".(|."0 1~i.&#)":

J, 23 chars (boolean only)

*/1&p:".(|."0 1~i.&#)":

": is a string conversion; i.&# produces a range of integers [0,len), and |."0 1~ is a rotation of the string by each successive integer of the range.

". converts the list of rotations back into numbers, 1&p: converts the list of numbers into booleans (i.e. "prime?" predicate), and */ is a multiply reduce over the booleans (i.e. and).

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Wow I really like this :) nicely done \$\endgroup\$ – Quillion Nov 13 '13 at 13:56
  • \$\begingroup\$ Add an {'nothing';'circular' and beat the Python submission :) \$\endgroup\$ – marinus Nov 14 '13 at 23:46
  • 1
    \$\begingroup\$ @marinus Done, though it really hurts my sense of aesthetics... The interface between the human and the program is always the least fun to code. \$\endgroup\$ – rationalis Nov 15 '13 at 4:03
  • \$\begingroup\$ Months after the fact, I finally just realized I could replace [:i.# with i.&#, which was bugging me at the time... L'esprit_de_l'escalier. Take that, GolfScript! \$\endgroup\$ – rationalis Aug 14 '14 at 8:41
7
\$\begingroup\$

Python, 106 chars

p=input();n=`p`
for i in n:
 n=n[1:]+n[0];e=2
 while`e`!=n:p*=int(n)%e;e+=1
print'cniortchuilnagr'[p<1::2]
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I see what you did there with the answer :) very clever \$\endgroup\$ – Quillion Nov 13 '13 at 15:29
  • 2
    \$\begingroup\$ Oh man! I just did mine in Python and I came up with "cniortchuilnagr" independently. \$\endgroup\$ – danmcardle Nov 14 '13 at 3:32
  • 1
    \$\begingroup\$ Whoa! I got the idea from codegolf.stackexchange.com/a/406/9395 \$\endgroup\$ – Daniel Lubarov Nov 14 '13 at 3:38
  • 3
    \$\begingroup\$ You can make this both shorter and correct if you use for i in n... otherwise, this will fail to rule out certain primes with more than 10 digits. \$\endgroup\$ – boothby Nov 14 '13 at 19:02
  • \$\begingroup\$ @boothby good idea, thanks! \$\endgroup\$ – Daniel Lubarov Nov 14 '13 at 19:47
7
\$\begingroup\$

Mathematica 62 61

f@s_ := And @@ PrimeQ[FromDigits@StringRotateLeft[s, #] & /@ Range@9]

Usage

f["1193"]

True

f["11939"]

True

f["1456"]

False

f["193939"]

True

f["1111111"]

False

f["7"]

True

f["23"]

False

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You can use FromDigits instead of ToExpression. \$\endgroup\$ – alephalpha Nov 13 '13 at 2:27
  • \$\begingroup\$ I had no idea that FromDigits could handle strings! \$\endgroup\$ – DavidC Nov 13 '13 at 2:34
5
\$\begingroup\$

Mathematica, 75 64

And@@PrimeQ[FromDigits/@NestList[RotateLeft,IntegerDigits@#,9]]&
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can save a few characters by using RotateRight or RotateLeft to rotate the digits. \$\endgroup\$ – DavidC Nov 13 '13 at 0:45
  • \$\begingroup\$ @DavidCarraher: Thanks, it saves quite a few, actually. How at one point I must have thought my elaborate Part trick would be shorter, I find most puzzling, but even now, you're still a good three characters ahead. \$\endgroup\$ – Marcks Thomas Nov 13 '13 at 13:13
5
\$\begingroup\$

Ruby, 110 109 chars

require'mathn'
x=gets.chop.split''
puts (0..x.size).all?{|n|x.rotate(n).join.to_i.prime?}?:circular:'nothing'
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You can shorten 1 character by using Symbol instead of String for :circular. \$\endgroup\$ – manatwork Nov 15 '13 at 9:31
3
\$\begingroup\$

R, 139

a=scan()
p=0
A=nchar(a)
S=substr
for(i in 1:A){b=as.integer(paste0(S(a,i+1,A),S(a,1,i)));p=p+!sum(!b%%1:b)<3}
c('nothing','circular')[!p+1]
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Python3.3, 160C

def m():
 s=input()
 r=range
 for i in r(len(s)):
  a=int(s)
  if all(a%i for i in r(2,a)):return 0
  s=s[1:]+s[:1]
 return 1 
print("cniortchuilnagr"[m()::2])
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

APL, 53

'nothing' 'circular'[1+^/{⌊/⍵|⍨1↓⍳⍵-1}¨⍎¨{⍵⌽∆}¨⍳⍴∆←⍞]
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Smalltalk, 195 chars

[:x|r:=[:n|(n\\10)*(10 raisedTo:n log floor)+(n//10)].s:=OrderedCollection with:x.[(m:=r value:s last)=x]whileFalse:[s add:m].^(s allSatisfy:[:each|each isPrime])ifTrue:['circular']ifFalse:['nothing']]

formatted

[:x|
  r:=[:n|(n\\10)*(10 raisedTo:n log floor)+(n//10)].
  s:=OrderedCollection with:x.
  [(m:=r value:s last)=x]whileFalse:[s add:m].
  ^(s allSatisfy:[:each|each isPrime])ifTrue:['circular']ifFalse:['nothing']]
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Japt, 23 bytes

Would obviously be a hell of a lot shorter without the unnecessarily strict output requirement, which accounts for more than half the score here.

ÆìéX jÃ×g`Í(ˆg circÔ³`¸

Try it (includes all test cases)

ÆìéX jÃ×g`...`¸     :Implicit input of integer U
Æ                   :Map each X in the range [0,U)
 ì                  :   Convert U to digit array
  éX                :   Rotate right X times and convert back to integer
     j              :  Is prime?
      Ã             :End map
       ×            :Reduce by multiplication
        g           :Index into (0-based)
         `...`      :  Compressed string "circular nothing"
              ¸     :  Split on spaces
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Husk, 22 19 bytes

?¨ÿċ◊¨¨ø±¨ΛoṗdSṀṙŀd

Try it online!

-3 bytes from Jo King. (simplified using )

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can simplify that last bit of logic for 19 bytes \$\endgroup\$ – Jo King Oct 11 at 8:43
2
\$\begingroup\$

05AB1E, 7 6 bytes

-1 thanks to @ovs!

gL._pP

Outputs 1 if a circular prime, and 0 if not! :D

Try it online!

This is actually my first effortful code answer in this site! Yey!

How?

g         # Get the number of digits in the input number.
 L        # Push a list of all numbers from 1 to the length.
  ._      # For each number 'n' in the list, rotate the input to to the left n times and push a list of all outcomes.
    p     # Is each rotation a prime? If prime, convert that number to 1, else convert it to 0.
     P    # Push the product of all 1's or 0's (if a rotation is not prime, the product should be zero).
          # Print the product automatically.

05AB1E, 17 16 bytes

Again -1 thanks to @ovs!

gL._pP“‹ë“si“ÒŽ“

This code follows the output standard suggested by the test cases. I wrote this just in case my previous answer is invalid. If it is not, please count 6B as my score!

Try it online!

How again?

gL._pP              # Works just like the previous answer.
      “‹ë“          # Push the string "nothing" from the 05AB1E dictionary.
          s         # Bring back the number output again.
           i        # If the number is 1...
            “ÒŽ“    # Push the string "circular" again from the 05AB1E dictionary.

Thanks to @Kevin Cruijssen's tip on compressing strings! :)

Edit: Wow, I noticed that both of my answers are currently the shortest (during the time of writing). That is kind of ironic for a first effortful answer. That means I won!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ My interpretation of the spec was the same as yours until I looked through the solutions. Pretty sure now that we have to output the words in the spec and the comments on the challenge would seem to back that up. \$\endgroup\$ – Shaggy Oct 10 at 19:36
  • \$\begingroup\$ @Shaggy Yea, but a Mathematica answer claims that it outputs "True" and "False" for output. \$\endgroup\$ – SunnyMoon Oct 10 at 19:49
  • 1
    \$\begingroup\$ If you rotate the input by the input length, you still get the input. This means gL works instead of g<Ý. And for this the builtin ā (length range) exists. \$\endgroup\$ – ovs Oct 11 at 7:47
  • \$\begingroup\$ @ovs Indeed you are right! \$\endgroup\$ – SunnyMoon Oct 11 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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