Is it a Cyclops number? "Nobody" knows!

67

1

Task:

Given an integer input, figure out whether or not it is a Cyclops Number.

What is a Cyclops number, you may ask? Well, it's a number whose binary representation only has one 0 in the center!

Test Cases:

Input | Output | Binary  | Explanation
--------------------------------------
0     | truthy | 0       | only one zero at "center"
1     | falsy  | 1       | contains no zeroes
5     | truthy | 101     | only one zero at center
9     | falsy  | 1001    | contains two zeroes (even though both are at the center)
10    | falsy  | 1010    | contains two zeroes
27    | truthy | 11011   | only one zero at center
85    | falsy  | 1010101 | contains three zeroes
101   | falsy  | 1100101 | contains three zeroes
111   | falsy  | 1101111 | only one zero, not at center
119   | truthy | 1110111 | only one zero at center

Input:

  • An integer or equivalent types. (int, long, decimal, etc.)

  • Assume that if evaluating the input results in an integer overflow or other undesirable problems, then that input doesn't have to be evaluated.

Output:

  • Truthy or falsy.

  • Truthy/falsy output must meet the used language's specifications for truthy/falsy. (e.g. C has 0 as false, non-zero as true)

Challenge Rules:

  • Input that is less than 0 is assumed to be falsy and thus does not have to be evaluated.

  • If the length of the binary representation of the number is even, then the number cannot be a Cyclops number.

General Rules:


This is my first Programming Puzzles & Code Golf challenge, so any feedback on how I should improve would be much appreciated!

Tau

Posted 2019-03-08T02:18:09.707

Reputation: 1 935

25

Note: This is A129868

– tsh – 2019-03-08T02:40:27.547

35+1 for the 2800 year late pop culture reference in the title – Sanchises – 2019-03-08T09:21:52.693

what is the maximum number that is be tested? – Serverfrog – 2019-03-08T13:06:45.897

@Serverfrog since I did not specify a limit, assume that any positive integer can be tested. – Tau – 2019-03-08T14:09:07.943

Is binary input allowed? – Qwertiy – 2019-05-25T08:22:30.913

Answers

11

Japt, 8 bytes

1¥¢q0 äè

Run it online

Explanation:

1¥¢q0 äè   
                                                              119
  ¢          // Convert the input into a binary string        "1110111"
   q0        // Split the string on "0"                       ["111","111"]
      ä      // Reduce each item by:                            a     b
       è     //   Seeing how many times a is found in b       [1]
 1¥          // == 1; See if the result equals 1              True                                         

The idea is to split the binary string at 0, which would yield two items if there is only one 0. Then we see if the first item matches the second to ensure it is palindromic. If the binary string contains multiple 0s, then the reduce would return a multi-item array and that would fail the ==1 condition. If the binary string does contain one 0, but is not palindromic, äè will return 0 because b contains 0 matches of a.

Oliver

Posted 2019-03-08T02:18:09.707

Reputation: 7 160

1Took my pre-caffeinated brain a couple of seconds to see what was happening here! Nicely done. should also work. – Shaggy – 2019-03-08T09:55:19.090

1I don't know Japt, but if I understand correctly it does the following: ¤ = convert to binary; q0 = split on 0s; äè I'm not entirely sure..; and the flag -N converts lists to NaN, but leaves 0 and 1 the same. For the äè part I can see that 119 is [111,111] after the split, which äè changes to 1; and 85 is [1,1,1,1] after the split, which äè changes to [1,1,1]. Could you explain how .ä("è") works? – Kevin Cruijssen – 2019-03-08T14:36:37.070

2@KevinCruijssen I added an explanation. I hope that helps. – Oliver – 2019-03-08T15:04:10.683

@KevinCruijssen, no better time to learn Japt ;) As well as that, I'm also working on a new interpreter for Japt, with a load of new features.

– Shaggy – 2019-03-08T17:12:54.523

1Is NaN falsey in Japt? (i.e. if you perform an if-else with that as the condition does the if get executed? "Truthy/falsy output must meet the used language's specifications for truthy/falsy") Also 2 yields 2 which I doubt is falsey (but might be if Japt is like 05AB1E). – Jonathan Allan – 2019-03-08T18:16:43.327

@JonathanAllan assuming that Japt is like JavaScript (which i'm assuming is true since it's just transpired from JS), NaN would be considered falsy.

– Tau – 2019-03-09T17:10:21.930

@Tau ...but not 2 (which is yielded by inputting 2) I believe; which would mean this is not currently conforming to spec. – Jonathan Allan – 2019-03-09T17:14:27.657

1JS assumes that any integer other than 0 is considered truthy... however, if 2 is returning 2 as truthy, then this submission may need to be reworked. – Tau – 2019-03-09T17:26:33.970

I think replacing äè with , as I mentioned above, should solve the issue @JonthanAllan raised. – Shaggy – 2019-03-09T20:54:44.590

Your code was almost a cyclops program. – mbomb007 – 2019-08-02T21:47:51.063

21

Python 2, 30 bytes

lambda n:(2*n^2*n+3)**2==8*n+9

Try it online!

Note that 2*n^2*n+3 is the bitwise xor of 2*n and 2*n+3, because that's Python's operator precedence.

xnor

Posted 2019-03-08T02:18:09.707

Reputation: 115 687

1Would it be acceptable to return lambda n:(2*n^2*n+3)**2-8*n-9, with a return value of 0 for cyclops numbers? – Eric Duminil – 2019-03-08T09:14:38.437

2This yields TRUE for n = -1 – user2390246 – 2019-03-08T11:28:29.940

3@user2390246 this problem is clearly not intended for negatives- if it was, all accepting solutions would need to be negatives (and the way that python implements integers would mean that no solutions should accept in python) – DreamConspiracy – 2019-03-08T20:13:57.863

@DreamConspiracy Can you explain more? – Solomon Ucko – 2019-03-08T20:52:43.690

@SolomonUcko The rules specifically say that negative input is falsy and does not have to be evaluated. – jaxad0127 – 2019-03-08T20:57:40.760

3@SolomonUcko negative numbers are typically stored in twos complement representation. Consider first fixed size integers (32 bit for example). Among other properties, TCR requires that the MSB is 1 in negative numbers, and 0 in positive. This would immediately require that all positive outputs are false. In python we have even more of a problem though. Negative numbers implicitly have an infinite sequence of 1s in the most significant direction. Good luck trying to find the middle of that – DreamConspiracy – 2019-03-08T21:01:33.403

2@user2390246 The problem was since edited to clarify that our code doesn't need to work for negatives. It could be handled for 2 bytes by appending >1. – xnor – 2019-03-09T03:36:37.603

18

x86 Machine Code, 17 bytes

8D 47 01 31 F8 89 C2 F7 D2 0F AF C2 8D 44 78 02 C3

The above bytes define a function that accepts a 32-bit integer input value (in the EDI register for this example, following a common System V calling convention, but you could actually pick pretty much any input register you wanted without affecting the size of the resulting code), and returns a result (in the EAX register) indicating whether the input value is a Cyclops number.

The input is assumed to be an unsigned integer, since the challenge rules state that we can ignore negative values.

The decision logic is borrowed from Neil's answer: since a Cyclops number has the form \$ n = (2 ^ k + 1) (2 ^ { k - 1 } - 1) \$, we can use a series of bit-twiddling operations to check the input.

Note: The return value is truthy/falsy, but the semantics are reversed, such that the function will return falsy for a Cyclops number. I claim this is legal because machine code doesn't have "specifications for truthy/falsy", which is the requirement in the question. (See below for an alternative version if you think this is cheating.)

In assembly language mnemonics, this is:

; EDI = input value
; EAX = output value (0 == Cyclops number)
8D 47 01           lea    eax, [edi + 1]          ; \ EAX = ((EDI + 1) ^ EDI)
31 F8              xor    eax, edi                ; /
89 C2              mov    edx, eax                ; \ EDX = ~EAX
F7 D2              not    edx                     ; /
0F AF C2           imul   eax, edx                ; EAX *= EDX
8D 44 78 02        lea    eax, [eax + edi*2 + 2]  ; EAX  = (EAX + (EDI * 2) + 2)
C3                 ret                            ; return, with EAX == 0 for Cyclops number

Try it online!


As promised, if you think it's cheating to invert the semantics of truthy/falsy even in machine code where there are no real standards or conventions, then add three more bytes, for a total of 21 bytes:

; EDI = input value
; AL  = output value (1 == Cyclops number)
8D 47 01           lea    eax, [edi + 1]          ; \ EAX = ((EDI + 1) ^ EDI)
31 F8              xor    eax, edi                ; /
89 C2              mov    edx, eax                ; \ EDX = ~EAX
F7 D2              not    edx                     ; /
0F AF C2           imul   eax, edx                ; EAX *= EDX
8D 44 78 01        lea    eax, [eax + edi*2 + 1]  ; EAX  = (EAX + (EDI * 2) + 1)
40                 inc    eax                     ; EAX += 1
0F 94 C0           setz   al                      ; AL = ((EAX == 0) ? 1 : 0)
C3                 ret                            ; return, with AL == 1 for Cyclops number

The first half of this code is the same as the original (down through the imul instruction). The lea is almost the same, but instead of adding a constant 2, it only adds a constant 1. That's because the following inc instruction increments the value in the EAX register by 1 in order to set the flags. If the "zero" flag is set, the setz instruction will set AL to 1; otherwise, AL will be set to 0. This is the standard way that a C compiler will generate machine code to return a bool.

Changing the constant added in the lea instruction obviously doesn't change the code size, and the inc instruction is very small (only 1 byte), but the setz instruction is a rather whopping 3 bytes. Unfortunately, I can't think of any shorter way of writing it.

Cody Gray

Posted 2019-03-08T02:18:09.707

Reputation: 2 639

4

This is so fast, I think it deserves to be shown off by testing all numbers up to a large value: Try it online!

– Deadcode – 2019-03-09T05:24:38.183

It should actually be even faster, @Deadcode. :-) Demonstrating it with inline assembly adds some overhead, but my old trick of jumping to a string of bytes (see e.g., this answer) has stopped working with TIO's compiler, and writing code to print the results directly in assembly is too much work to bother with. This is one of those unusual cases, though, where optimizing for size is not at odds with optimizing for speed. This is pretty much the way you'd write the code in asm if you were going for speed over size.

– Cody Gray – 2019-03-09T05:36:25.200

By consensus, it not unacceptable to return a status flag in an asm submission https://codegolf.stackexchange.com/a/165020/84624 and https://stackoverflow.com/questions/48381234/is-it-considered-bad-practice-to-use-the-flags-register-as-a-boolean-return-valu. If so, you could - 3 from your second answer.

– 640KB – 2019-03-10T22:01:13.733

9

JavaScript (Node.js), 20 bytes

p=>~p==(p^=p+1)*~p/2

Try it online!

Maybe this is correct, maybe.

Thanks Grimy, 1 byte saved.


JavaScript (Node.js), 32 bytes

f=(p,q)=>p&1?f(p/2,q+q|2):!(p^q)

Try it online!


JavaScript (Node.js), 34 bytes

p=>/^(1*)0\1$/.test(p.toString(2))

Try it online!

tsh

Posted 2019-03-08T02:18:09.707

Reputation: 13 072

20 – Grimmy – 2019-03-08T15:26:07.577

Test, not match – edc65 – 2019-03-09T17:11:30.230

1@edc65 Did you find out any failed testcase? – tsh – 2019-03-11T01:53:02.030

2@tsh .test not .match – ASCII-only – 2019-03-11T06:50:13.507

@ASCII-only Wow, sound reasonable... How can you read this? – tsh – 2019-03-11T07:22:40.843

@tsh read what lol – ASCII-only – 2019-03-11T08:19:42.320

9

Regex (ECMAScript), 60 58 57 60 58 bytes

The input \$n\$ is in unary, as the length of a string of xs.

SPOILER WARNING: For the square root, this regex uses a variant of the generalized multiplication algorithm, which is non-obvious and could be a rewarding puzzle to work out on your own. For more information, see an explanation for this form of the algorithm in Find a Rocco number.

-2 bytes by allowing backtracking in the search for \$z\$
-1 byte thanks to Grimy, by searching for \$z\$ from smallest to largest instead of vice versa
+3 bytes to handle zero
-2 bytes by moving the square root capture outside the lookahead

This works by finding \$z\$, a perfect square power of 2 for which \$n=2(n-z)+\sqrt{z}+1\$. Only the largest perfect square power of 2 not exceeding \$n\$ can satisfy this, but due to a golf optimization, the regex tries all of them starting with the smallest. Since each one corresponds to a cyclops number, only the largest one can result in a match.

^(x*)(?!(x(xx)+)\2*$)(x(x*))(?=(?=(\4*)\5+$)\4*$\6)x\1$|^$

Try it online!

^                 # N = tail
(x*)              # tail = Z, with the smallest value that satisfies the following
                  # assertions (which is no different from the largest value that
                  # would satisfy them, since no more than one value can do so);
                  # \1 = N - Z

(?!(x(xx)+)\2*$)  # Assert Z is a power of 2

# Assert Z is a perfect square, and take its square root
(x(x*))           # \4 = square root of Z; \5 = \4 - 1; tail = N - \1 - \4
(?=(\4*)\5+$)     # iff \4*\4 == Z, then the first match here must result in \6==0
(?=\4*$\6)        # test for divisibility by \4 and for \6==0 simultaneously

# Assert that N == \1*2 + \4 + 1. If this fails, then due to a golf optimization,
# the regex engine will backtrack into the capturing of \4, and try all smaller
# values to see if they are the square root of Z; all of these smaller values will
# fail, because the \4*\4==Z multiplication test only matches for one unique value
# of \4.
x\1$

|^$               # Match N==0, because the above algorithm does not

Deadcode

Posted 2019-03-08T02:18:09.707

Reputation: 3 022

OP clarified that 0 should be truthy, so this currently doesn't solve the challenge. – Grimmy – 2019-03-08T16:17:45.890

1Isn't a simple ^(1*)0\1$ enough? – Embodiment of Ignorance – 2019-03-08T16:32:56.033

4@EmbodimentofIgnorance Only if the input were in binary. That would trivialize a lot of challenges; consistently using unary input where applicable is much more interesting. – Deadcode – 2019-03-08T16:58:10.323

7

Japt, 25 19 10 9 bytes

¢êÅ©1¶¢èT

Thanks to @Shaggy for -1 byte

Try it online!

Quintec

Posted 2019-03-08T02:18:09.707

Reputation: 2 801

9 bytes – Shaggy – 2019-03-08T07:54:25.053

7

Perl 6, 23 bytes

{.base(2)~~/^(1*)0$0$/}

Try it online!

Regex based solution

Jo King

Posted 2019-03-08T02:18:09.707

Reputation: 38 234

7

Mathematica (Wolfram language), 32 31 bytes

1 byte saved thanks to J42161217!

OddQ@Log2[#+Floor@Sqrt[#/2]+2]&

Try it online!

Pure function taking an integer as input and returning True or False. Based on the fact (fun to prove!) that a number n is Cyclops if and only if n plus the square root of n/2 plus 2 rounds down to an odd power of 2. (One can replace Floor by either Ceiling or Round as long as one also replaces +2 by +1.) Returns True on input 0.

Greg Martin

Posted 2019-03-08T02:18:09.707

Reputation: 13 940

1you can save 1 byte by using Log2[#+Floor@Sqrt... – J42161217 – 2019-03-08T20:09:45.550

and 1 more using √() instead of Sqrt[]

– attinat – 2019-04-20T20:16:52.557

Is the byte count correct? TIO gives 32 bytes for the current program. – mbomb007 – 2019-08-02T21:51:29.953

@mbomb007 aha, the TIO didn't incorporate J42161217's 1-byte savings. Fixed. – Greg Martin – 2019-08-03T01:45:41.623

Was there a reason you didn't use what attinat suggested? – mbomb007 – 2019-08-03T03:03:57.913

no, just laziness – Greg Martin – 2019-08-03T06:33:49.373

6

Ruby, 24 bytes

->x{x+x+2==(1+x^=x+1)*x}

Try it online!

G B

Posted 2019-03-08T02:18:09.707

Reputation: 11 099

Nice. There might be a shorter version with different assignments and precedence, but I couldn't find any. – Eric Duminil – 2019-03-08T16:49:13.683

5

Japt, 8 bytes

¢ðT ¥¢Êz

Thanks to Luis felipe de Jesus Munoz for fixing my submission!

Try it Online!

Old regex-based solution, 15 bytes

¤f/^(1*)0\1$/ l

Returns 1 for true, 0 for false.

Try it Online!

Embodiment of Ignorance

Posted 2019-03-08T02:18:09.707

Reputation: 7 014

Well played, I should really learn regular expressions sometime. :) +1 – Quintec – 2019-03-08T03:01:45.350

1@Quintec Regex is awesome :) – Embodiment of Ignorance – 2019-03-08T03:02:10.523

Update: found shorter way :) – Quintec – 2019-03-08T03:11:18.933

18 bytes – Luis felipe De jesus Munoz – 2019-03-08T11:54:30.297

1@LuisfelipeDejesusMunoz Thanks, that's a really nice use of the == operator! – Embodiment of Ignorance – 2019-03-08T16:35:03.880

I'll get your bounty setup for this on Monday; I'm not online over the weekend and, if I do it now, I'll only forget about it. – Shaggy – 2019-03-08T17:15:36.747

4

Jelly,  8  7 bytes

-1 thanks to Erik the Outgolfer (use isPalindrome built-in, ŒḂ, instead of ⁼Ṛ$)

B¬ŒḂ⁼SƊ

A monadic Link accepting an integer which yields 1 (truthy) or 0 (falsey).

Try it online!

How?

B¬ŒḂ⁼SƊ - Link: integer             e.g. 1    9          13         119
B       - to base 2                      [1]  [1,0,0,1]  [1,1,0,1]  [1,1,1,0,1,1,1]
 ¬      - logical NOT (vectorises)       [0]  [0,1,1,0]  [0,0,1,0]  [0,0,0,1,0,0,0]
      Ɗ - last three links as a monad:
  ŒḂ    -   is a palindrome?             1    1          0          1
     S  -   sum                          0    2          1          1
    ⁼   -   equal?                       0    0          0          1

Jonathan Allan

Posted 2019-03-08T02:18:09.707

Reputation: 67 804

Looks like you actually had the clever idea before me, but its cleverness isn't obvious (Bċ0⁼1ȧŒḂ is also 8 bytes), ⁼Ṛ$ is the same as ŒḂ for -1. Also, you don't need to handle negative numbers. – Erik the Outgolfer – 2019-03-08T17:35:55.967

Thanks Erik, the is palindrome built-in slipped my mind for some reason! – Jonathan Allan – 2019-03-08T18:11:22.350

Actually, you can also use ṚƑ in its place nowadays, so you might want to remember it like that (the most important Ƒs). – Erik the Outgolfer – 2019-03-08T20:23:38.203

4

Regex (ECMAScript), 53 47 bytes

-6 bytes thanks to both Deadcode and Grimy

^((?=(x*?)(\2((x+)x(?=\5$))+x$))(?!\2{6})\3x)*$

Try it online!

H.PWiz

Posted 2019-03-08T02:18:09.707

Reputation: 10 962

In the course of fully commenting and proving your regex (not quite finished yet), I got it down to 50 bytes: ^((?=(x(x*?))(\3((x+)(?=\6$))+xx$))(?!\2{6})x\4)*$ (Try it online!)

– Deadcode – 2019-03-09T05:19:53.450

4

Haskell, 32 bytes

f n=or[2*4^k-2^k-1==n|k<-[0..n]]

Try it online!

xnor

Posted 2019-03-08T02:18:09.707

Reputation: 115 687

4

Brachylog, 8 bytes

ḃD↔Dḍ×ᵐ≠

This is a predicate that succeeds if its input is a Cyclops number and fails if its input is not a Cyclops number. Success/failure is the most fundamental truthy/falsey concept in Brachylog.

Try it online! Or, find all truthy outputs up to 10000.

Explanation

          Input is an integer
ḃ         Get its binary representation, a list of 1's and 0's
 D        Call that list D
  ↔       When reversed...
   D      It's the same value D
    ḍ     Dichotomize: break the list into two halves
          One of these halves should be all 1's; the other should contain the 0
     ×ᵐ   Get the product of each half
       ≠  Verify that the two products are not equal

This succeeds only when given a Cyclops number, because:

  • If the binary representation isn't a palindrome, D↔D will fail; in what follows, we can assume it's a palindrome.
  • If there is more than one zero, both halves will contain at least one zero. So the products will both be zero, and ×ᵐ≠ will fail.
  • If there is no zero, both halves will contain only ones. So the products will both be one, and ×ᵐ≠ will fail.
  • That leaves the case where there is exactly one zero; since we already know we have a palindrome, this must be the central bit. It will appear in one half, causing that half's product to be zero; the other half will contain all ones, so its product will be one. Then we have 1 ≠ 0, ×ᵐ≠ succeeds, and the whole predicate succeeds.

DLosc

Posted 2019-03-08T02:18:09.707

Reputation: 21 213

3

J, 22 19 17 15 14 bytes

-3 bytes thanks to BolceBussiere !

-4 bytes thanks to ngn!

-1 byte thanks to Traws!

J, 14 bytes

1=1#.(*:|.)@#:

Try it online!

Galen Ivanov

Posted 2019-03-08T02:18:09.707

Reputation: 13 815

-3 Bytes by using +/=<:@# instead of ,@0-:1-.~] – Bolce Bussiere – 2019-04-11T02:52:00.177

@BolceBussiere Of course, that's much better! Thanks! – Galen Ivanov – 2019-04-11T07:34:52.530

1#=1++/­­­­­­­ – ngn – 2019-04-12T00:48:21.540

1(#=1++/)@(*|.)@#: – ngn – 2019-04-12T01:01:42.610

@ngn Thank you! Nice and simple code! – Galen Ivanov – 2019-04-12T03:58:46.863

11=1#.1-(*|.)@#: – ngn – 2019-04-12T14:25:15.047

@ngn Addicted to J? – Galen Ivanov – 2019-04-12T17:16:46.850

1i don't know enough j to use it but it's fun to learn from other people's code by trying to shorten it – ngn – 2019-04-12T17:49:03.830

1-1 byte 1=1#.(*:|.)@#: – Traws – 2019-05-25T15:03:51.700

@Traws Nice, thank you! – Galen Ivanov – 2019-05-25T18:41:12.767

3

Ruby, 27 24 bytes

Convert to binary and check with a regex. Returns 0 if true, nil if false.

-3 bytes thanks to GB.

->n{"%b"%n=~/^(1*)0\1$/}

Try it online!

For two bytes more, there's a direct port of the Python solution:

->n{(2*n^2*n+3)**2==8*n+9}

Eric Duminil

Posted 2019-03-08T02:18:09.707

Reputation: 701

@GB Thank you very much! – Eric Duminil – 2019-03-08T12:24:52.847

3

05AB1E, 8 (or 9) bytes

bD0¢sÂQ*

Try it online or verify all test cases.

Returns 1 if truthy; 0 or any positive integer other than 1 as falsey. In 05AB1E only 1 is truthy and everything else is falsey, but I'm not sure if this is an allowed output, or if the output should be two consistent and unique values. If the second, a trailing Θ can be added so all outputs other than 1 become 0:

Try it online or verify all test cases.

Explanation:

b     # Convert the (implicit) input-integer to a binary-string
 D    # Duplicate it
  0¢  # Count the amount of 0s
 s    # Swap to get the binary again
  ÂQ  # Check if it's a palindrome
 *    # Multiply both (and output implicitly)

  Θ   # Optionally: check if this is truthy (==1),
      # resulting in truthy (1) or falsey (0)

An arithmetic approach would be 10 bytes:

LoD<s·>*Iå

Try it online or verify all test cases.

Explanation:

Creates a sequences using the algorithm \$a(n) = (2^n-1)*(2*2^n+1)\$, and then checks if the input-integer is in this sequence.

L        # Create a list in the range [1, (implicit) input-integer]
 o       # For each integer in the list, take 2 to the power this integer
  D<     # Create a copy, and decrease each value by 1
  s·     # Get the copied list again, and double each value
    >    # Then increase each value by 1
  *      # Multiply the numbers at the same indices in both lists
     Iå  # Check if the input-integer is in this list
         # (and output the result implicitly)

Kevin Cruijssen

Posted 2019-03-08T02:18:09.707

Reputation: 67 575

Having 1 as truthy and all other numbers as falsy is acceptable for this challenge, since other languages (e.g. C and TI-BASIC) have similar truthy/falsy definitions (0/non-zero for both). As long as what's considered truthy or falsy matches with the language's specifcations, then it's fair game. – Tau – 2019-03-08T14:13:48.153

3

R, 37 33 bytes

(x=scan())%in%(2*4^(n=0:x)-2^n-1)

Try it online!

R doesn't have a built-in for converting to binary, so I simply used one of the formulae from OEIS to calculate a list of terms from the sequence.

n<-0:x generates a generous list of starting values. 2*4^(n<-0:x^2)-2^n-1) is the formula from OEIS, and then it checks whether the input appears in that sequence using %in%.

-2 bytes by not having to handle negative inputs. -2 bytes by remembering I can change <- to =.

user2390246

Posted 2019-03-08T02:18:09.707

Reputation: 1 391

3

Excel, 97 63 Bytes

=A1=2*4^(ROUND(LOG(A1,4),0))-2^(ROUND(LOG(A1,4),0))-1

Calculates 2 numbers:

Twice the nearest Power of 4
>Num|Binary|2*Power4|Binary
> 1| 1| 2* 1= 2| 10
> 2| 10| 2* 4= 8| 1000
> 4| 100| 2* 4= 8| 1000
> 20| 10100| 2*16=32|100000

 

1 Plus the square root of the nearest Power of 4
>Num|Binary|1+√Power4|Binary
> 1| 1|1+ √1= 2| 10
> 2| 10|1+ √4= 3| 11
> 4| 100|1+ √4= 3| 11
> 20| 10100|1+ √16= 5| 101

Then subtract the second number from the first:

>Num|Binary|2*Power4|Binary|1+√Power4|Binary|a-b|Binary
> 1| 1| 2* 1= 2| 10|1+ √1= 2| 10| 0| 0
> 2| 10| 2* 4= 8| 1000|1+ √4= 3| 11| 5| 101
> 4| 100| 2* 4= 8| 1000|1+ √4= 3| 11| 5| 101
> 20| 10100| 2*16=32|100000|1+ √16= 5| 101| 27| 11011

And compare this result with the original number

Old Method

=DEC2BIN(A1)=REPLACE(REPT("1",1+2*INT(IFERROR(LOG(A1,2),0)/2)),1+IFERROR(LOG(A1,2),0)/2,1,"0")

Start with the Log-base-2 of A1 and round it down the nearest even number, then add 1.

Next create a string of that many "1"s, and replace the middle character with a "0" to create a Cyclops number with a binary length that is always odd, and the same as or 1 less than the binary length of A1

Then, compare it with the Binary representation of A1

Chronocidal

Posted 2019-03-08T02:18:09.707

Reputation: 571

3

C (gcc),  29 28  27 bytes

Saved 1 byte thanks to @ceilingcat

A port of the 21-byte JS answer by @tsh.

f(p){p=2*~p==~(p=-~p^p)*p;}

Try it online!

Arnauld

Posted 2019-03-08T02:18:09.707

Reputation: 111 334

3

C (gcc), 26 bytes

f(n){n=~n==(n^=-~n)*~n/2;}

Try it online!

Port of Neil's answer. Relies on implementation-defined ordering of operations.

C++ (clang), 38 bytes

int f(int n){return~n==(n^=-~n)*~n/2;}

Try it online!

Can't omit the types in C++, can’t omit the return in clang, otherwise identical.

Grimmy

Posted 2019-03-08T02:18:09.707

Reputation: 12 521

1I would prefer that C++ answers be differentiated from C answers by using return instead of the fragile and platform-dependent implicit accumulator return value exploit. – Deadcode – 2019-03-08T17:20:45.523

2I would also like the rules to require standard-compliance, but they don’t, so not making use of this would just be bad golf. C++ (clang) requires the return, making this 38 bytes. – Grimmy – 2019-03-08T17:27:40.897

Then you can get around this by having C (gcc) and C++ (clang) in your answer instead of C (gcc) and C++ (gcc). I've now done that. – Deadcode – 2019-03-08T17:33:38.003

2

Jelly, 9 bytes

BŒḂaB¬S=1

Try it online!

Nick Kennedy

Posted 2019-03-08T02:18:09.707

Reputation: 11 829

2

Retina 0.8.2, 38 37 bytes

.+
$*
+`^(1+)\1
$+0
10
1
^((1+)0\2)?$

Try it online! Link includes test cases. Edit: After clarification, previous solution didn't handle zero correctly. Explanation:

.+
$*

Convert from decimal to unary.

+`^(1+)\1
$+0
10
1

Convert from unary to binary, using the method from the Retina wiki.

^((1+)0\2)?$

Check for the same number of 1s before and after the 0, or an empty string (which is how the above conversion handles zero).

Neil

Posted 2019-03-08T02:18:09.707

Reputation: 95 035

2

Attache, 22 bytes

{Flip@_=_∧1=0~_}@Bin

Try it online!

Alternatives

27 bytes: {BitXor[2*_,2*_+3]^2=8*_+9}

27 bytes: {BitXor@@(2*_+0'3)^2=8*_+9}

27 bytes: {Palindromic@_∧1=0~_}@Bin

28 bytes: {BitXor[...2*_+0'3]^2=8*_+9}

28 bytes: {BitXor[…2*_+0'3]^2=8*_+9}

28 bytes: {Same@@Bisect@_∧1=0~_}@Bin

29 bytes: {_[#_/2|Floor]=0∧1=0~_}@Bin

30 bytes: Same@Bin@{_+2^Floor[Log2@_/2]}

30 bytes: {_[#_/2|Floor]=0and 1=0~_}@Bin

Conor O'Brien

Posted 2019-03-08T02:18:09.707

Reputation: 36 228

1

Regex (ECMAScript), 65 59 57 58 bytes

+1 byte to handle 0 correctly

^((((x*)xx)\3)x)?(?=(\1*)\2*(?=\4$)((x*)(?=\7$)x)*$)\1*$\5

Try it online!

Works by asserting the input is of the form \$ (2^k - 1) (2^{k+1} + 1) \$. Ties Deadcode's answer but with a completely different algorithm.

Grimmy

Posted 2019-03-08T02:18:09.707

Reputation: 12 521

1

APL(NARS), 57 char, 114 bytes

{⍵≤0:1⋄k=m←⌈k←2÷⍨≢v←{(2⍴⍨⌊1+2⍟⍵)⊤⍵}⍵:0⋄((,1)≡∪v∼⍦0)∧∼m⊃v}

test:

  f←{⍵≤0:1⋄k=m←⌈k←2÷⍨≢v←{(2⍴⍨⌊1+2⍟⍵)⊤⍵}⍵:0⋄((,1)≡∪v∼⍦0)∧∼m⊃v}
  ⎕fmt f¨0 1 5 12 27 85 101 119
┌8───────────────┐
│ 1 0 1 0 1 0 0 1│
└~───────────────┘

This below would be (modulus bugs) the function that would convert a positive integer number omega in one array of digits in base alpha:

{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}

RosLuP

Posted 2019-03-08T02:18:09.707

Reputation: 3 036

1

Batch, 39 37 bytes

@cmd/cset/a"m=%1^-~%1,!(m/2*(m+2)-%1)

Explanation: A Cyclops number has the form \$ n = (2 ^ k + 1) (2 ^ { k - 1 } - 1) \$. The bitwise XOR then results in \$ m = 2 ^ k - 1 \$ from which we can recalculate \$ n = \lfloor \frac m 2 \rfloor ( m + 2 ) \$. This can then be used to test whether \$ n \$ was a Cyclops number.

Neil

Posted 2019-03-08T02:18:09.707

Reputation: 95 035

1

Excel, 101 107 bytes

-6 bytes thanks to @Chronocidal.

=AND(ISEVEN(LOG(A1,2)),MID(DEC2BIN(A1),LEN(DEC2BIN(A1))/2+1,1)="0",LEN(SUBSTITUTE(DEC2BIN(A1),1,))=1)

Performs 3 checks:

  • Odd length
ISEVEN(LOG(A1,2))
  • Middle character is 0
MID(DEC2BIN(A1),LEN(DEC2BIN(A1))/2+1,1)="0"
  • There is a single 0
LEN(SUBSTITUTE(DEC2BIN(A1),1,))=1

Wernisch

Posted 2019-03-08T02:18:09.707

Reputation: 2 534

1Save 6 bytes by changing ISODD(LEN(DEC2BIN(A1))) to ISEVEN(LOG(A1,2)) – Chronocidal – 2019-03-08T13:11:21.467

1

C++, 142 138 107 106 104 88 85 82 72 bytes

-10 bytes thanks to ceilingcat

int f(int n){int c=1;for(;n&1;n/=2)++c;while(n/=2,--c,n&1);return!n&!c;}

Ungolfed:

bool is_cyclops(int n)
{
    int ones = 1;
    while ((n & 1) == 1)
    {
        ++ones;
        n /= 2;
    }
    while (--ones, n /= 2, (n & 1) == 1)
    {
        // nothing to do
    }
    return n == 0 && ones == 0;
}

Noodle9

Posted 2019-03-08T02:18:09.707

Reputation: 2 776

1

C++ (clang), 72 68 67 bytes

As with Neil's and Grimy's solutions, this works by asserting that the input is of the form \$(2^k-1)(2^{k+1}+1)\$.

5 bytes were dropped thanks to Arnauld, by changing ((x)+1) to -~(x) and ((x)-1) to ~-(x), and then changing n-a*-b to n+a*b.

int f(int n){int z,k=0;while((z=n+~-(1<<k)*~(1<<++k))>0);return!z;}

Try it online!

Ungolfed:

bool is_cyclops_number(int n)
{
    for (int k=0;; k++)
    {
        int z = n - ((1<<k)-1) * ((1<<(k+1))+1);
        if (z == 0)
            return true;
        if (z < 0)
            return false;
    }
}

C (gcc), 41 bytes

Returns zero for true and nonzero for false.

k;f(n){for(k=0;n+~-(1<<k)*~(1<<++k)>0;);}

Try it online!

This demonstrates why I hate the implicit accumulator return value exploit that is commonly used in C submissions and less often in C++ submissions. It's fragile and very much platform dependent. Here, it depends upon the comparison operator > not changing the value of the accumulator.

Deadcode

Posted 2019-03-08T02:18:09.707

Reputation: 3 022

Suggest for(k=1;n+~-k*~(k*=2)>0;); instead of for(k=0;n+~-(1<<k)*~(1<<++k)>0;); – ceilingcat – 2019-05-24T22:43:11.433

1

VBA, 41 36 Bytes

x=2^Int([Log(A1,4)]):?[A1]=2*x^2-x-1

Run in the Immediate window, with Explicit Declaration turned off. Input is cell A1 of the active sheet. Outputs True/False to the immediate window.

Uses the same logic as my Excel Answer to find the Cyclops number of the same number of bits (or 1 bit shorter if there are an even number!) and then compares that with the input.

Saves some bytes when calculating Cyclops numbers by reducing them to the form y = 2x^2 - x - 1 (where x = n-1 for the nth Cyclops number, or x = 2^Int(Log([A1])/Log(4)) to find the largest Cyclops number with a lesser-or-equal number of bits) and storing x in a variable

(-5 Bytes thanks to Taylor Scott!)

Chronocidal

Posted 2019-03-08T02:18:09.707

Reputation: 571

1Instead of converting the log's base using log division, you can change it directly using [...] notation as [(Log(A1,4)] – Taylor Scott – 2019-03-08T18:40:46.523

1

Stax, 9 7 bytes

ç8┤-½Θ■

Run and debug it

recursive

Posted 2019-03-08T02:18:09.707

Reputation: 8 616

1

PHP, 74 bytes

function($x){return($c=strlen($a=decbin($x)))&1&&trim($a,1)===$a[$c/2|0];}

Try it online!

Totally naïve non-mathematical approach, just strings.

function cyclops( $x ) {
    $b = decbin( $x );     // convert to binary string (non-zero left padded)
    $l = strlen( $b );     // length of binary string
    $t = trim( $b, 1 );    // remove all 1's on either side
    $m = $b[ $l / 2 |0 ];  // get the middle "bit" of the binary string
    return 
        $l & 1 &&          // is binary string an odd length?
        $t === $m;         // is the middle char of the binary string the same as
                           // the string with left and right 1's removed? (can only be '0')
}

Or 60 bytes based on @Chronocidal's algorithm above.

function($x){return decbin($x)==str_pad(0,log($x,2)|1,1,2);}

Try it online!

640KB

Posted 2019-03-08T02:18:09.707

Reputation: 7 149

1

Haskell, 82 bytes

import Text.Printf
(`all`[(==)<*>reverse,("0"==).filter(<'1')]).flip($).printf"%b"

And a port of xnor's Python solution:

Haskell, 47 bytes

import Data.Bits
\n->(2*n`xor`(2*n+3))^2==8*n+9

Joseph Sible-Reinstate Monica

Posted 2019-03-08T02:18:09.707

Reputation: 556

1

K (ngn/k), 19 bytes

{1=(~x)+/~a&|a:2\x}

Try it online!

{ } function with argument x

2\x the bits of x

a: assign to a

a&|a and between a and its reverse (|a)

~ not

+/ sum

(~x) use "not x" as the initial value for the sum. this is to correct for 2\x returning an empty list of bits when x is 0

1= compare with 1

ngn

Posted 2019-03-08T02:18:09.707

Reputation: 11 449

1

dc, 62 60 bytes

[2~rd0<B]dsBx1kz2/szsi[1r-si]sC[zlz=Cli*siz0<M]sMz1=Cz1<Mlip

Try it online!

dc has no native truthy/falsy values (conditionals either execute a macro or they don't); using 1 for truthy and 0 for falsy, I hope that's ok.

[2~rd0<B]dsBx          # Basic breakdown into binary. Every digit is a stack entry. Luckily this
                       # also leaves an extra 0 on the stack.
1k                     # Set precision to one - needed it at 0 for the binary-ifier.
z2/sz                  # Divide the stack depth by 2 and store it in 'z'. This is why we're lucky
                       # that the binary-ifier leaves an extra bit on the stack! Numbers with even 
                       # numbers of binary digits will now have an odd number & this value will be
                       # (whatever).5 which... isn't a valid stack depth.
si                     # Seed 'i' which is our truthiness register w/ that extra 0
[1r-si]sC              # Macro 'C' toggles the top of stack between 0 and 1 by subtracting it from 1.
                       # It stores this in 'i'. This is the only way 'i' ever becomes 1.
[zlz=Cli*siz0<M]sM     # First we test if we're at the position of the stack that matches up with 
                       # 'z', and run 'C' if so. Thus, if we're in the 'Cyclops' position (the
                       # middle), we'll flip that from a 0 to a 1 or vice versa. Next we load 'i'
                       # and multiply it by top of stack, putting that back in 'i'. For the first half
                       # this whole thing does nothing but multiply stuff by zero. In the middle
                       # position (if there is one) it sets 'i' to 1 if it's a zero. For the rest of
                       # the digits, it multiplies by '1' if things are ok, and '0' if there's another
                       # (Cyclops-invalidating) zero.
z1=Cz1<M               # 1 and 0 don't work w/o special treatment. Run 'C' if it's one of these, 
                       # otherwise start 'M'
lip                    # Print 'i'

Golfed off two bytes because my brain was fried and I was using a wasteful, convoluted method of toggling between 1 and 0.

brhfl

Posted 2019-03-08T02:18:09.707

Reputation: 1 291

0

Factor, 69 bytes

: f ( n -- ? ) >bin [ dup reverse = ] [ [ 48 = ] count 1 = ] bi and ;

Try it online!

Galen Ivanov

Posted 2019-03-08T02:18:09.707

Reputation: 13 815

0

Java (OpenJDK 8), 135 130 bytes

Uses the Formula described here: A129868

(n)->java.util.stream.IntStream.range(0,16).map(r->((Double)(Math.pow(2,2*r+1)-(Math.pow(2,r)-1)-2)).intValue()).anyMatch(c->c==n)

Try it online!

Serverfrog

Posted 2019-03-08T02:18:09.707

Reputation: 245

Why do you say it doesn't work with all positive integers? It works fine up to a million, and I see no reason why it'd stop working.

– Grimmy – 2019-03-08T16:02:30.933

https://codegolf.stackexchange.com/questions/181128/is-it-a-cyclops-number-nobody-knows/181174?noredirect=1#comment436477_181128 "...any positive integer can be tested". Example where it wont work anymore: 2096127. This is due to that i only test the first 11 of the OEIS A129868 Numbers. could do more maybe, but it will not work vor ANY positive integer i think – Serverfrog – 2019-03-08T16:09:25.163

2Okay, so this doesn't actually answer the problem, you should edit it to make it work or delete it. Marking an answer as non-competing isn't a free pass, it should still be valid. – Grimmy – 2019-03-08T16:13:30.603

It's funny how you first say everything is fine, and after i point you where the OP post that limit (that wasn't really defined before this answer was posted) you aggressively force to make it work now or deleting it without seemingly to know the timeline between answer and the point it was invalid :P – Serverfrog – 2019-03-08T16:21:35.310

Sorry, I didn't mean to come across as aggressive. I also didn't say everything was fine, I just asked to be sure whether the answer was valid. Also the timeline isn't really relevant, if the answer is currently invalid it should be fixed or deleted. – Grimmy – 2019-03-08T16:37:37.477

1Currently it is unkown if this or any other answer is valid because OP don't really defined what he meant with any positive integer as a integer could be 2 things, one has a maximum value the other not. And after my last change it is working with the 32-bit signed Integer – Serverfrog – 2019-03-08T16:41:10.637

Let us continue this discussion in chat.

– Grimmy – 2019-03-08T16:46:03.507

0

Swift, 161 bytes

func c(a:Int)->Int{
    let b=String(a,radix:2)
    let f=b.firstIndex(of:"0")
    return a>=0 && f==b.lastIndex(of:"0") && f?.encodedOffset==b.count/2 ? 1 : 0
}

Try it online!

onnoweb

Posted 2019-03-08T02:18:09.707

Reputation: 211

0

Perl 5 -p, 32 bytes

$_=(sprintf'%b',$_)=~/^(1*)0\1$/

Try it online!

Xcali

Posted 2019-03-08T02:18:09.707

Reputation: 7 671

0

Java, 201 bytes (compilable)

Hmm, a different approach in java, runnable on commandline (so there is much to cut out).

class Z{public static void main(String[]a{a=Integer.toBinaryString(Integer.valueOf(a[0])).split("0");System.out.println(a.length==0?1:(a.length!=2?1:a[0].length()-a[1].length()+a.length-2)==0?1:0);}}

prints 0 for non cyclops and 1 for cyclops numbers.

68CodingMonkeys

Posted 2019-03-08T02:18:09.707

Reputation: 1

Welcome to PPCG! I think you can remove public. Is there a ) missing after String[]a? a.length==0 -> a.length < 1, again later (maybe?). – Stephen – 2019-03-11T18:54:14.013

0

PHP

The shortest code should be this:

preg_match('`^(?<l>1*)0\k{l}$`', decbin($n));

Here the script to test it:

$inputs = [
    0,
    1,
    5,
    9,
    10,
    27,
    85,
    101,
    111,
    119,
];


function isCyclop($n) {
    return preg_match('`^(?<l>1*)0\k{l}$`', decbin($n));
}

foreach ($inputs as $input) {
    echo "$input : ".(isCyclop($input)?'truthy':'falsy').PHP_EOL;
}

Asenar

Posted 2019-03-08T02:18:09.707

Reputation: 101

0

Java, 96 bytes

n->{String[]a=Integer.toBinaryString(n).split("0");return n==0||a.length==2&&a[0].equals(a[1]);}

Try it online!

Benjamin Urquhart

Posted 2019-03-08T02:18:09.707

Reputation: 1 262

0

Perl 6 (26 bytes)

{so .base(2)~~/^(1*)0$0$/}

bb94

Posted 2019-03-08T02:18:09.707

Reputation: 1 831

You can remove the so, since the output can just be truthy/falsey, but it ends up the same as my answer

– Jo King – 2019-03-19T02:17:23.400

0

Gaia, 10 9 bytes

b:ṭ¤0C1=∧

Try it online!

Verify All Test Cases

b:		% convert to binary and dup
  ṭ		% is it a palindrome?
        ∧	% and
   ¤0C		% is the count of zeros
      1=	% equal to 1?
		% implicit print top of stack

Giuseppe

Posted 2019-03-08T02:18:09.707

Reputation: 21 077

0

Pip, 87 bytes

a:qTa<=1{((a%2)=0)?(x:"0".x)(x:"1".x)a//:2}1=a?x:"1".xsc:x^"0"x=0|#x%2=1&(c0)=(c1)&#c=2

Try it online!

Kenneth Taylor

Posted 2019-03-08T02:18:09.707

Reputation: 183