Half, Half Half, and, Half

33

Consider the following number sequence:

\$ 0, \frac{1}{2}, \frac{1}{4}, \frac{3}{4}, \frac{1}{8}, \frac{3}{8}, \frac{5}{8}, \frac{7}{8}, \frac{1}{16}, \frac{3}{16}, \frac{5}{16}, \frac{7}{16}, \frac{9}{16}, \frac{11}{16}, \frac{13}{16}, \frac{15}{16}, \frac{1}{32}, \frac{3}{32}, \frac{5}{32}, \dots \$

It enumerates all binary fractions in the unit interval \$ [0, 1) \$.

(To make this challenge easier, the first element is optional: You may skip it and consider the sequence starts with 1/2.)

Task

Write a program (complete program or a function) which...

Choose one of these behaviors:

  • Input n, output nth element of the sequence (0-indexed or 1-indexed);
  • Input n, output first n elements of the sequence;
  • Input nothing, output the infinite number sequence which you can take from one by one;

Rule

  • Your program should at least support first 1000 items;
  • You may choose to output decimals, or fractions (built-in, integer pair, strings) as you like;
    • Input / Output as binary digits is not allowed in this question;
  • This is , shortest codes win;
  • Standard loopholes disallowed.

Testcases

input output
1     1/2     0.5
2     1/4     0.25
3     3/4     0.75
4     1/8     0.125
10    5/16    0.3125
100   73/128  0.5703125
511   511/512 0.998046875
512   1/1024  0.0009765625

These examples are based on 0-indexed sequence with the leading 0 included. You would need to adjust the input for fitting your solution.

Read More

  • OEIS A006257
    • Josephus problem: \$ a_{2n} = 2a_n-1, a_{2n+1} = 2a_n+1 \$. (Formerly M2216)
    • 0, 1, 1, 3, 1, 3, 5, 7, 1, 3, 5, 7, 9, 11, 13, 15, 1, 3, 5, ...
  • OEIS A062383
    • \$ a_0 = 1 \$: for \$ n>0 \$, \$ a_n = 2^{\lfloor log_2n+1 \rfloor} \$ or \$ a_n = 2a_{\lfloor \frac{n}{2} \rfloor} \$.
    • 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 32, 32, 32, ...
  • A006257(n)/A062383(n) = (0, 0.1, 0.01, 0.11, 0.001, ...) enumerates all binary fractions in the unit interval [0, 1). - Fredrik Johansson, Aug 14 2006

tsh

Posted 2018-09-14T13:57:53.317

Reputation: 13 072

4"Input nothing, output the infinite number sequence one by one" Does it have to be one-by-one, or are we also allowed to output an infinite list (possible in Haskell, Elixir, 05AB1E, etc.)? – Kevin Cruijssen – 2018-09-14T15:14:06.020

Can I output a list of strings? e.g. "1/2" "1/4" "1/8"... – Barranka – 2018-09-14T15:21:58.773

@KevinCruijssen Infinite list is fine as long as you can take n elements from it later. – tsh – 2018-09-15T05:45:48.293

@Barranka I think it is acceptable. That is nothing different to print fractions to stdout. – tsh – 2018-09-15T05:46:30.413

When you say Input / Output as binary numbers is not allowed, you mean we can't write a function that returns a pair if ints, or a double in a language / implementation where double uses IEEE binary64 format? I hope you don't mean was have to parse an ASCII string if we want to take an integer input? Normal integer types are binary in languages like C. Or do you mean the input/output can't be an array or string of integer or ASCII zeros/ones?

– Peter Cordes – 2018-09-17T05:41:51.710

@PeterCordes I mean you cannot return / print a string with 0s and 1s. Should I edit it to make it clear? So, how should I describe this? – tsh – 2018-09-17T07:12:42.193

I'd say "input/output can't be a string or list of base-2 digits. A single binary integer or float is ok". I think that should be clear to people who are used to the common code-golf terminology of "convert to binary" meaning to turn an integer into a list of binary digits, and also clear to people who use low-level languages like C or assembly. It's a bit awkward; I feel like there should be a better way to phrase it, but that's the best I've got. (The first sentence is perfectly clear, I think, but maybe not to everyone. The 2nd sentence is just clarification.) – Peter Cordes – 2018-09-17T07:20:07.863

Answers

22

Haskell, 25 bytes

pred.until(<2)(/2).(+0.5)

Try it online!

Outputs decimals, one-indexed without the initial zero term.

Adds 0.5 to the input, then halves until the results is below 2, then subtracts 1. Using a pointfree expression saves 1 bytes over

f n=until(<2)(/2)(n+0.5)-1

xnor

Posted 2018-09-14T13:57:53.317

Reputation: 115 687

11

Java 10, 68 64 bytes

First try at code golf!

Option 1: find the n-th element (1-indexed)

-4 bytes thanks to @Kevin Cruijssen

n->{int x=0;for(;n>>++x!=1;);return((~(1<<x)&n)*2.+1)/(1<<x+1);}

This is an anonymous method that finds the n-th term by removing the most significant bit from n, doubling it and adding one, then dividing by the next highest power of 2.

Try it online!

Code walkthrough:

n->{                      // builds anonymous function with input n
int x=0;                  // stores floor of log(n) (base 2) for most significant digit
for(;n>>++x!=1;);         // calculates floor of log(n) by counting right shifts until 1
return((~(1<<x)&n)        // removes most significant digit of n
*2.+1)                     // multiplies 2 and adds 1 to get the odd numerator
/(1<<x+1);}               // divides by the next highest power of 2 and returns`

Will edit if it's necessary to print the final value instead of returning it.

TCFP

Posted 2018-09-14T13:57:53.317

Reputation: 371

Welcome to PPCG, good to have you with us :) – Shaggy – 2018-09-14T19:39:10.700

Hi, welcome to PPCG! Great first answer, +1 from me. Currently it's the same byte-count as my Java answer, but you can still golf some parts of your answer to make it shorter than mine: The {} after the loop can be a ; instead; you can remove the space after the return; 2.0 can be 2.; And changing the n>>x!=1;x++, 1<<x, and 1<<x+1 to n>>x++!=1;, 1<<x-1, 1<<x respectively also saves a byte. Try it online: 64 bytes. Enjoy your stay!

– Kevin Cruijssen – 2018-09-14T20:43:32.203

Oh, and if you haven't seen it yet: Tips for golfing in Java and Tips for golfing in <all languages> are both pretty interesting to read through. :)

– Kevin Cruijssen – 2018-09-14T20:44:22.183

See my 30 bytes answer, originally based on yours but golfed and golfed and golfed.

– Olivier Grégoire – 2018-09-17T09:36:30.563

9

MathGolf, 5 4 bytes

╫\╨]

Try it online!

How it would look like with the operator working correctly

╫\)╨]   (")" adds 1 to TOS, making rounding behave as expected)

Try it online!

Explanation

╫     Left-rotate all bits in input
 \    Swap top two elements on stack, pushing the input to the top
  ╨   Round up to nearest power of 2
   ]  Wrap in array (just for pretty printing)

I took my inspiration from this question to solve the problem, my "own" solution was around 10-12 bytes I think.

I had intended for the round up to closest power of 2 to return the number itself if it was a number of two, but due to a mistake it rounds to the next power of two (e.g. 4 -> 8 instead of 4 -> 4). This will have to be fixed later, but now it saves me one byte.

maxb

Posted 2018-09-14T13:57:53.317

Reputation: 5 754

2I don't know MathGolf but if the ] serves no other purpose than formatting the output, I'd say you don't need to include it in your byte count. – Shaggy – 2018-09-14T17:17:14.707

2I was unsure about it. Since the stack is printed on output as a joined string, it outputs a stack with the numbers 1 and 2 as 12. If that still counts I'll remove a byte – maxb – 2018-09-14T17:21:24.773

I think you should leave it in. It sometimes saves a byte to output the stack as one string, sometimes it will cost you a byte. – H.PWiz – 2018-09-14T17:40:57.583

@H.PWiz that was my original thinking, since it seems fair to use the strengths of your language. Some languages only print the top of the stack when finished, some print it as a list. Usually it's a 1 byte difference, but it's part of the challenge. – maxb – 2018-09-14T18:52:22.970

8

Java 10, 89 85 70 69 68 bytes

v->{for(float j,t=2;;t*=2)for(j=1;j<t;j+=2)System.out.println(j/t);}

Port of @Emigma's 05AB1E answer, so outputs decimals indefinitely as well.
-15 bytes thanks to @Arnauld.

Try it online.

Explanation:

v->{                      // Method with empty unused parameter and no return-type
  for(float j,t=2;;       //  Loop `t` from 2 upwards indefinitely,
                   t*=2)  //  doubling `t` after every iteration
    for(j=1;j<t;          //   Inner loop `j` in the range [1, `t`),
                j+=2)     //   in steps of 2 (so only the odd numbers)
      System.out.println( //    Print with trailing new-line:
        j/t);}            //     `j` divided by `t`

Kevin Cruijssen

Posted 2018-09-14T13:57:53.317

Reputation: 67 575

1

How often can I say that I half your byte count? Well, I think this is the first time ;-)

– Olivier Grégoire – 2018-09-17T09:41:22.003

@OlivierGrégoire Dang, now that is an impressive Java answer. :) I saw your 37-byte version as comment on TCFP's answer, but you even stripped off more bytes. It looks so extremely simple now in your 30-byte version, but it's still ingenious how you've golfed it from the initial version. Well done! – Kevin Cruijssen – 2018-09-17T10:03:37.010

8

Perl 6, 19 bytes

{($_+.5)/2**.msb-1}

Try it online!

nwellnhof

Posted 2018-09-14T13:57:53.317

Reputation: 10 037

7

Python 3, 33 bytes

lambda n:(8*n+4)/2**len(bin(n))-1

Try it online!

Outputs decimals, one-indexed without the initial zero term.

xnor

Posted 2018-09-14T13:57:53.317

Reputation: 115 687

7

Java (JDK 10), 30 bytes

n->(n+.5)/n.highestOneBit(n)-1

Try it online!

Returns the nth item in the sequence.

This answer is originally a succession of golfs of TCFP's Java answer. In the end, the golfs didn't look like the original answer anymore (though the math used is the same) so I decided to post the golfs as a separate answer instead of simply commenting on the TCFP's answer. So if you like this answer, go upvote TCFP's answer as well! ;-)

Intermediate golfs were:

n->{int x=0;for(;n>>++x!=1;);return((~(1<<x)&n)*2.+1)/(1<<x+1);} // 64 bytes (TCFP's answer when I started golfing)
n->{int x=0;for(;n>>++x!=1;);x=1<<x;return((~x&n)*2.+1)/x/2;}    // 61 bytes
n->{int x=n.highestOneBit(n);return((~x&n)*2.+1)/x/2;}           // 54 bytes
n->{int x=n.highestOneBit(n);return((~x&n)+.5)/x;}               // 50 bytes
n->((n&~(n=n.highestOneBit(n)))+.5)/n                            // 37 bytes
n->(n-(n=n.highestOneBit(n))+.5)/n                               // 34 bytes
n->(n+.5)/n.highestOneBit(n)-1                                   // 30 bytes, current score

Olivier Grégoire

Posted 2018-09-14T13:57:53.317

Reputation: 10 647

And I was sitting here thinking my answer was as short as I could make it, you come along and cut it by more than half! Amazing stuff, definitely deserves a +1 from me. – TCFP – 2018-09-17T13:25:30.607

@TCFP It was an iterative process over the span of several hours. I actually posted each intermediate golfing as a comment to your answer, but deleted them as I found better golfs. Thanks for the praise ;-) – Olivier Grégoire – 2018-09-17T13:32:33.347

6

05AB1E, 11 8 bytes

Saved 3 bytes thanks to Kevin Cruijssen.

∞oDÅÉs/˜

Try it online!

Explanation

∞         # start an infinite list [1...
 o        # calculate 2**N
  D       # duplicate
   ÅÉ     # get a list of odd numbers up to 2**N
     s/   # divide each by 2**N
       ˜  # flatten

Emigna

Posted 2018-09-14T13:57:53.317

Reputation: 50 798

1

-1 byte by using (infinite list starting at 1): ∞oεDÅÉs/}˜

– Kevin Cruijssen – 2018-09-14T15:12:44.067

@KevinCruijssen: Cool! That's a command I hadn't seen before. Thanks :) – Emigna – 2018-09-15T08:55:54.103

1Ah, and nice way of saving two more bytes due to the implicit mapping.. Hadn't even thought about that, lol.. – Kevin Cruijssen – 2018-09-15T09:41:43.150

1:O how is this possible. You condensed the ~2 page question into 8 bytes. – Cullub – 2018-09-17T02:21:15.930

I was thinking using the prime numbers and a list of [1,2,4,4,8,8,8,8,16,16,...,2**n] and prepending the correct indexed prime followed by a /... But that wasn't working so well. Well, but not 8-bytes well. Something like 9LoDÅP)ζ. – Magic Octopus Urn – 2018-10-26T16:02:03.190

Or, more accurately, LoDÅPs/˜. – Magic Octopus Urn – 2018-10-26T16:08:14.670

5

Jelly, 9 bytes

Bṙ1Ḅ,æċ2$

Try it online!

Dennis

Posted 2018-09-14T13:57:53.317

Reputation: 196 637

5

PowerShell, 40 bytes

for($i=2;;$i*=2){1..$i|?{$_%2}|%{$_/$i}}

Try it online!

Outputs the infinite sequence as decimal values. Given language limitations, will eventually run into precision problems, but easily handles the first 1000 entries.

Starts by setting $i=2, then enters a for loop. Each iteration, we construct a range from 1..$i and pull out the odd values with |?{$_%2}. Those are fed into their own inner loop, where we divide each to get the decimal |%{$_/$i}. Those are left on the pipeline and output when the pipeline is flushed after every for iteration. Each iteration we're simply incrementing $i by $i*=2 to get the next go-round.

AdmBorkBork

Posted 2018-09-14T13:57:53.317

Reputation: 41 581

5

Haskell, 35 32 bytes

Edit: -3 bytes thanks to @Delfad0r.

[(y,2^x)|x<-[1..],y<-[1,3..2^x]]

This is an infinite list of integer pairs.

Try it online!

nimi

Posted 2018-09-14T13:57:53.317

Reputation: 34 639

5

Haskell, 40 bytes

s=(1,2):[(i*2+u,j*2)|(i,j)<-s,u<-[-1,1]]

Try it online!

Infinite sequence as pairs of integers (starting from (1,2)).

Quite a bit longer than @nimi's answer, but the approach is completely different, so I decided to post it anyway.

This solution is based on the following observation.

Consider the infinite sequence $$ \left\{\frac{1}{2},\frac{1}{4},\frac{3}{4},\frac{1}{8},\frac{3}{8},\frac{5}{8},\frac{7}{8},\frac{1}{16},\frac{3}{16},\ldots\right\} $$ and apply the following steps.

  • Replace every number \$\frac{i}{j}\$ in the sequence with the list \$\left\{\frac{2i-1}{2j},\frac{2i+1}{2j}\right\}\$: $$ \left\{\left\{\frac{1}{4},\frac{3}{4}\right\},\left\{\frac{1}{8},\frac{3}{8}\right\},\left\{\frac{5}{8},\frac{7}{8}\right\},\left\{\frac{1}{16},\frac{3}{16}\right\},\ldots\right\} $$
  • Join all the lists into a single sequence: $$ \left\{\frac{1}{4},\frac{3}{4},\frac{1}{8},\frac{3}{8},\frac{5}{8},\frac{7}{8},\frac{1}{16},\frac{3}{16},\ldots\right\} $$
  • Add \$\frac{1}{2}\$ at the beginning of the sequence: $$ \left\{\frac{1}{2},\frac{1}{4},\frac{3}{4},\frac{1}{8},\frac{3}{8},\frac{5}{8},\frac{7}{8},\frac{1}{16},\frac{3}{16},\ldots\right\} $$

Notice how you get back to the sequence you started with!

The solution exploits this fact (together with Haskell's laziness) to compute the sequence s.

Delfad0r

Posted 2018-09-14T13:57:53.317

Reputation: 1 688

4

Python 2 - 68 66 bytes

-2 bytes thanks to Kevin

from math import*
def g(n):a=2**floor(log(n,2));print(n-a)*2+1,2*a

Try it Online!

Don Thousand

Posted 2018-09-14T13:57:53.317

Reputation: 1 781

You can golf 1 byte by changing return 2*(n-a) to return(n-a)*2. And you could save an additional byte by using Python 2 instead of 3, so return can be print (with parenthesis). – Kevin Cruijssen – 2018-09-14T15:27:02.650

2@KevinCruijssen For someone who doesn't use Python, you certainly are a better Python programmer than me. – Don Thousand – 2018-09-14T15:27:41.703

Hehe. :D Simple things like this comes with experience I guess. I'm on this site for about two years now I think (EDIT: Since April 2016). I sometimes even suggests things to golf for answers that are written in languages I had never seen before.. Some basic things work in most languages. For example, last week I suggested a golf for a T-SQL answer, and I once suggested a golf in a Red answer. xD

– Kevin Cruijssen – 2018-09-14T15:33:36.297

244 bytes using len and bin instead of log. – ovs – 2018-09-15T06:16:07.370

@ovs 42 bytes.

– Jonathan Frech – 2018-09-15T10:54:12.473

@JonathanFrech I recommended lambda n:(n-~n)/2**len(bin(n)[2:])-1 (36 bytes) before, but deleted the comment, as the answer would converge to xnor's. – ovs – 2018-09-15T11:01:26.820

4

Python 3, 53 51 bytes

  • Saved two bytes thanks to mypetlion; reusing default parameters to reset n.
def f(m=2,n=1):n<m and print(n/m)&f(m,2+n)or f(m+m)

Try it online!

Jonathan Frech

Posted 2018-09-14T13:57:53.317

Reputation: 6 681

Swap the parameters to save 2 bytes: def f(m=2,n=1):n<m and print(n/m)&f(m,n+2)or f(m+m) – mypetlion – 2018-09-14T16:14:39.193

1@mypetlion Cool, thank you! – Jonathan Frech – 2018-09-14T16:17:35.107

4

R, 42 bytes

function(n)c(y<-2^(log2(n)%/%1)*2,2*n-y+1)

Try it online!

Returns a pair Denominator,Numerator. Uses the formula \$\begin{equation}N = 2*\left(n-2^{\lfloor \log_2(n)\rfloor}\right)+1\end{equation}\$ from the Josephus sequence and \$\begin{equation}D = 2^{\lfloor \log_2(n)\rfloor+1}\end{equation}\$ from the other sequence. Happily we are able to re-use the denominator as the two formulas have quite a lot in common!

Giuseppe

Posted 2018-09-14T13:57:53.317

Reputation: 21 077

3

Racket, 92 91 bytes

(define(f k(m 2)(n 1))(if(> k 0)(if(=(+ n 1)m)(f(- k 1)(+ m m))(f(- k 1)m(+ n 2)))(/ n m)))

Try it online!

  • Saved a byte thanks to Giuseppe -- removing superfluous whitespace.

Jonathan Frech

Posted 2018-09-14T13:57:53.317

Reputation: 6 681

3

MATL, 8 bytes

BnWGEy-Q

Try it online!

Returns Numerator, then Denominator. Uses the same method as my R answer, although it's a bit more efficient.

Explanation, with input 5:

           # implicit input 5
B          # convert to array of bits
           # STACK: [[1 0 1]]
n          # length (place of Most Significant Bit)
           # STACK: [3]
W          # elementwise raise 2^x
           # STACK: [8]
G          # paste input
           # STACK: [8, 5]
E          # double
           # STACK: [8, 10]
y          # copy from below
           # STACK: [8, 10, 8]
-          # subtract
           # STACK: [8, 2]
Q          # increment
           # STACK: [8, 3]
           # implicit end of program, display stack contents

Giuseppe

Posted 2018-09-14T13:57:53.317

Reputation: 21 077

2

Shakespeare Programming Language, 426 bytes

,.Ajax,.Ford,.Act I:.Scene I:.[Exeunt][Enter Ajax and Ford]Ajax:You be the sum ofyou a cat.Ford:You cat.Scene V:.Ford:Is twice you nicer I?If solet usScene X.You be twice you.Let usScene V.Scene X:.Ford:Remember twice you.You be the sum oftwice the remainder of the quotient betweenI you a cat.Open heart.You big big big big big cat.Speak thy.Recall.Open heart.You be twice the sum ofa cat a big big cat.Speak thy.Let usAct I.

Try it online!

Outputs the sequence infinitely as both numbers separated by a space, with each item being separated by a newline.

JosiahRyanW

Posted 2018-09-14T13:57:53.317

Reputation: 2 600

Love it. Lol You be twice the sum of a cat – Cullub – 2018-09-17T02:24:30.657

Actually, it's "twice the sum ofa cat a big big cat" (i.e. 10 for some reason). – JosiahRyanW – 2018-09-17T02:39:20.760

2

Excel 48 28 Bytes

Saved 20 bytes (!) thanks to tsh

=(A1+0.5)/2^INT(LOG(A1,2))-1

=MOD(A1+0.5,2^(INT(LOG(A1,2))))/2^INT(LOG(A1,2))

Assumes value in A1, output is in decimal. If you want the output to be in fraction, you can create a custom format for the output cell as "0/###0" and it will show it as fraction.

Explanation: Difficult to explain, since there is a shortcut taken to get to this formula. Basically the numerator is a bit shift left of the input, and the denominator is the next power of 2 higher than the number input.

I originally started with Excel built in functions for BITLSHIFT and BITRSHIFT, but they will shift the entire 48 bits which is not what you want. The functions DEC2BIN (and BIN2DEC) have a limit of -512 to 511 (10 bits) so this wouldn't work. Instead I had to rebuild the number with a modulus of the original number, then times two, then add 1 (since the left digit would always be 1 before a shift).

=MOD(A1                        Use MOD for finding what the right digits are
       +0.5                    this will later add the left "1" to the right digits
           ,2^INT(LOG(A1,2)))) Take Log base 2 number of digits on the right
                               this creates the numerator divided by 2 (explained later)
/ 2^INT(LOG(A1,2))             The denominator should be 2^ (Log2 + 1) but instead of 
                               adding a 1 here, we cause the numerator to be divided by 2 instead
                               This gives us a fraction.  In the numerator, we also added .5
                               instead of 1 so that we wouldn't need to divide it in both the
                               numerator and denominator
Then tsh showed how I could take the int/log out of the mod and remove it from numerator/denominator. 

Examples: enter image description here

Keeta - reinstate Monica

Posted 2018-09-14T13:57:53.317

Reputation: 938

What about =(A1+0.5)/2^INT(LOG(A1,2))-1? – tsh – 2018-09-18T09:50:48.547

2

Python 2, 44 bytes

def f(n):m=2**len(bin(n))/4;return 2*n-m+1,m

Try it online!

Function returns a tuple of (numerator, denominator). An input of 0 is not handled (it was optional).

Chas Brown

Posted 2018-09-14T13:57:53.317

Reputation: 8 959

1return 2*n-m+1,m can be print-~n+n-m,m to save 2 bytes. – Kevin Cruijssen – 2018-09-14T20:56:39.153

2

C++, 97 75 71 bytes

-26 bytes thanks to tsh, ceilingcat, Zacharý

float f(int i){float d=2,n=1;while(--i)n=d-n==1?d*=2,1:n+2;return n/d;}

Testing code :

std::cout << "1\t:\t" << f(1) << '\n';
std::cout << "2\t:\t" << f(2) << '\n';
std::cout << "3\t:\t" << f(3) << '\n';
std::cout << "4\t:\t" << f(4) << '\n';
std::cout << "10\t:\t" << f(10) << '\n';
std::cout << "100\t:\t" << f(100) << '\n';
std::cout << "511\t:\t" << f(511) << '\n';
std::cout << "512\t:\t" << f(512) << '\n';

HatsuPointerKun

Posted 2018-09-14T13:57:53.317

Reputation: 1 891

You may just omit if(!i)return 0; since 0 is not required in the challenge. – tsh – 2018-09-17T07:58:44.257

1When trying to golf C-like language. You should avoid using while but try for. for(;exp;) is as same as while(exp) but you can write two more other statement into it. Prefer ?: instead of if else, which would be shorter in most cases. – tsh – 2018-09-17T08:02:01.417

1I don't think you need the (...) around d-n-1. – Zacharý – 2018-09-23T20:38:59.513

1

C (gcc), 63 bytes

No input, prints infinite sequence:

f(i,j){for(i=1,j=2;;i+=2,i>j&&(j*=2,i=1))printf("%d/%d ",i,j);}

Try it online!

Annyo

Posted 2018-09-14T13:57:53.317

Reputation: 231

360 bytes. – Jonathan Frech – 2018-09-14T15:38:18.847

1

Building on @JonathanFrech 59 bytes

– ceilingcat – 2019-10-27T04:10:54.197

1

JavaScript (ES6), 44 bytes

Returns the \$n\$-th term, 1-indexed.

f=(n,p=q=1)=>n?f(n-1,p<q-2?p+2:!!(q*=2)):p/q

Try it online!

Arnauld

Posted 2018-09-14T13:57:53.317

Reputation: 111 334

1

Ruby, 42 bytes

1.step{|i|(1..x=2**i).step(2){|j|p [j,x]}}

Try it online!

Prints integer pairs infinitely, starting from 1/2.

Kirill L.

Posted 2018-09-14T13:57:53.317

Reputation: 6 693

1

JavaScript (Node.js), 30 bytes

f=(n,d=.5)=>d>n?n/d:f(n-d,d*2)

Try it online! 0-indexed. Started out as a port of my Batch answer but I was able to calculate in multiples of \$\frac{1}{2}\$ which saved several bytes.

Neil

Posted 2018-09-14T13:57:53.317

Reputation: 95 035

1

Ruby, 31 bytes

->x{(2r*x+1)/2**x.bit_length-1}

Try it online!

G B

Posted 2018-09-14T13:57:53.317

Reputation: 11 099

1

><>, 19 18 bytes

Using xnor's idea, fixed by Jo King, -1 byte by making better use of the mirrors and another -2 bytes by Jo King because the ! was superfluous and ; is not required.

2*1+\1-n
2:,2/?(

Try it online!

PidgeyUsedGust

Posted 2018-09-14T13:57:53.317

Reputation: 631

You should be checking if it is smaller than 2 first, otherwise the first element is -0.25. Fix for the same amount of bytes

– Jo King – 2018-09-17T22:58:44.453

Thanks! I also managed to remove another byte by reusing the mirrors. – PidgeyUsedGust – 2018-09-18T08:23:46.577

Why did you invert the condition? 16 bytes

– Jo King – 2018-09-18T08:27:08.890

Didn't notice that it would continue the loop. Are we allowed to not properly finish? – PidgeyUsedGust – 2018-09-18T08:29:48.213

Yeah, terminating with an error is fine as long as the OP doesn't specify otherwise – Jo King – 2018-09-18T08:30:58.487

1

Wolfram Language (Mathematica), 22 bytes

2^Mod[Log2[2#+1],1]-1&

Try it online!

alephalpha

Posted 2018-09-14T13:57:53.317

Reputation: 23 988

1

APL (Dyalog Unicode), 15 bytes

1-⍨.5∘+÷2*∘⌊2⍟⊢

Try it online!

Anonymous prefix lambda.

Thanks to Adám for 4 bytes and to Cows quack for 2 bytes.

How:

1-⍨.5∘+÷2*∘⌊2⍟⊢ ⍝ Anonymous lambda, argument ⍵ → 10
            2⍟⊢ ⍝ Log (⍟) of ⍵ in base 2. 2⍟10 → 3.32192809489...
           ⌊     ⍝ Floor. ⌊3.32192809489... → 3
        2*∘      ⍝ Take that power of 2. 2³ → 8
       ÷         ⍝ Use that as denominator
   .5∘+          ⍝ ⍵ + 0.5 → 10.5. Using that as numerator: 10.5÷8 → 1.3125
1-⍨              ⍝ Swap the arguments (⍨), then subtract. 1-⍨1.3125 → 1.3125-1 → 0.3125

J. Sallé

Posted 2018-09-14T13:57:53.317

Reputation: 3 233

1

C# (.NET Core), 69 bytes

a=>{int b=1,c=2;while(a-->1){b+=2;if(b>c){b=1;c*=2;}}return b+"/"+c;}

Try it online!

Ungolfed:

a=> {
    int b = 1, c = 2;   // initialize numerator (b) and denominator (c)
    while (a-- > 1)     // while a decrements to 1
    {
        b += 2;         // add 2 to b
        if (b > c)      // if b is greater than c:
        {
            b = 1;      // reset numerator to 1
            c *= 2;     // double denominator
        }
    }
    return b + "/" + c; // return fraction as string
}

Meerkat

Posted 2018-09-14T13:57:53.317

Reputation: 371

1

x86 machine code, 36 bytes

00000000: 4389 de46 5653 6800 0000 00e8 fcff ffff  C..FVSh.........
00000010: 83c3 0239 f37e edd1 e631 db43 ebe6 2564  ...9.~...1.C..%d
00000020: 2f25 6420                                /%d 

Prints the sequence infinitely.

The hexdump is unlinked, e.g. the address for printf is a placeholder.

Assembly:

section .text
	global func
	extern printf
func:
	inc ebx			;set numerator to 1
	mov esi, ebx
	inc esi			;set denominator to 2
	loop:
		push esi
		push ebx
		push fmt
		call printf
		add ebx, 2	;increment numerator by 2
		cmp ebx, esi
		jle loop	;if numerator<denominator (eg ebx/esi<1), repeat loop
		shl esi, 1	;double the denominator
		xor ebx, ebx
		inc ebx		;reset numerator to 1
		jmp loop
section .data
	fmt db '%d/%d '

Try it online!

Logern

Posted 2018-09-14T13:57:53.317

Reputation: 845

0

Zephyr, 82 bytes

set d to 2
while 1=1
for n from 1 to d/2
print((2*n)-1)/d
next
set d to d*2
repeat

Try it online!

Iterate over denominators 2, 4, 8, 16, ... forever. For each d (e.g. 8), iterate n from 1 up to d/2 (e.g. 1, 2, 3, 4). The desired odd-number numerators are then 2*n-1. Zephyr's built-in rational numbers mean we just do the division and print the result.

(I really think more languages should have built-in rational numbers!)

DLosc

Posted 2018-09-14T13:57:53.317

Reputation: 21 213

0

Batch, 73 bytes

@set/an=%1*2,d=1
:l
@if %d% leq %1 set/an-=d,d*=2&goto l
@echo %n%/%d%

Outputs 0/1 for an input of 0. Explanation: n is the numerator and d is the denominator. d is doubled each time until it exceeds the input, and the previous value of d is subtracted from n as it goes. This is slightly golfier than calculating n=%1*2+1-d separately.

Neil

Posted 2018-09-14T13:57:53.317

Reputation: 95 035

0

Appleseed, 76 bytes

(def s(lambda((d 2)(n 1))(if(> n d)(s(* d 2))(cons(list n d)(s d(+ n 2))))))

Defines a function s that, when called without arguments, returns an infinite list of (<numer> <denom>) pairs. Try it online!

Ungolfed

(def sequence
  (lambda ((denom 2) (numer 1))
    (if (less? denom numer)
      (sequence (* denom 2))
      (cons
        (list numer denom)
        (sequence denom (+ numer 2))))))

Same idea as Jonathan Frech's Python function (right down to the order of the default arguments being important), except here we cons each result onto the (infinite) recursive call instead of printing it.

DLosc

Posted 2018-09-14T13:57:53.317

Reputation: 21 213

0

Perl 5 -a, 53 bytes

map{say"$_/$.";--$F[0]||exit}grep$_%2,1..$.while$.*=2

Try it online!

1-indexed. First element is 1/2. Outputs the first n elements.

Xcali

Posted 2018-09-14T13:57:53.317

Reputation: 7 671

0

Perl 6, 38 bytes

(0,{(1,3...2**@_-1)X/2**@_}...*)>>.say

Try it online!

Outputs elements infinitely, starting from 0.

An infinite sequence itself ends up at 40 bytes

.5,{$/=.nude;($1-$0-1??$0+2!!.5)/$1}...*

Try it online!

Jo King

Posted 2018-09-14T13:57:53.317

Reputation: 38 234

0

Python 3, 71 bytes

n,d=0,1
for t in range(int(input())):
    n+=2
    if n>d:n=1;d*=2
print(n/d)

Index starts with 0 at 0.0 and 1 at 0.5 and so on.

Try it online!

Josh B.

Posted 2018-09-14T13:57:53.317

Reputation: 105

0

Stax, 8 bytes

▀`Ö²╬─}t

Run and debug it

This program uses stax's rational type. It takes a 1-based integer index as input, and produces that sequence element.

Unpacked, ungolfed, and commented, it looks like this.

Hc  double the input and copy it
:GY unset all but the highest bit, and store in register Y
-^  subtract (leaving all the other bits), then increment
yu* push the value in register Y, then multiply by its reciprocal

Run this one

recursive

Posted 2018-09-14T13:57:53.317

Reputation: 8 616

0

APL(NARS), 30 chars, 60 bytes

{⍵=0:0⋄(1+2×⍵-2*k)÷2*1+k←⌊2⍟⍵}

test:

f←{⍵=0:0⋄(1+2×⍵-2*k)÷2*1+k←⌊2⍟⍵}
  f¨0 1 2 3 4 5 6 7 8
0 0.5 0.25 0.75 0.125 0.375 0.625 0.875 0.0625 
  f¨511 512  10023
0.998046875 0.0009765625 0.2235717773 

RosLuP

Posted 2018-09-14T13:57:53.317

Reputation: 3 036

0

D, 66 bytes

T f(T)(T i){T d=2,n=1;while(--i)n=d-n==1?(d*=2)/d:n+2;return n/d;}

Try it online!

Port of @HatsuPointerKun's C++ answer.

grumble Comma expressions are pretty worthless in D grumble

Zacharý

Posted 2018-09-14T13:57:53.317

Reputation: 5 710

0

J, 20 bytes

(>:@+:@#.@}.,2^#)@#:

This verb take n and gives us the nth number in the list. n = 1 produces 1/2, etc...

explanation

(>:@+:@#.@}. , 2 ^ #)@#:
                     @#:  NB. The arg as list of binary digits, feed that to...
             ,            NB. the concatenation of... (first doing the left side)
         @}.              NB. remove the highest order bit and...
      @#.                 NB. convert back to decimal and...
   @+:                    NB. double it and...
 >:                       NB. add one (now we have the numerator)
               2 ^        NB. (now doing the right side) 2 raised to the...
                   #      NB. number of binary digits (the denominator)

Try it online!

Jonah

Posted 2018-09-14T13:57:53.317

Reputation: 8 729