text:
Generating Fermat primes
Given a number n, print the nth prime Fermat number, where the Fermat numbers are of the form 22k+1. This code should theoretically work for any n (i.e. don't hardcode it), although it is not expected to terminate for n > 4. (It should not return 4294967297 for n=5, as 4294967297 is not a prime number.)
Do note that while all Fermat primes are of the form 22n+1, not all numbers of the form 22n+1 are prime. The goal of this challenge is to return the n-th prime.
Test cases
0 -> 3
1 -> 5
2 -> 17
3 -> 257
4 -> 65537

Rules

Standard loopholes are disallowed.
0-indexing and 1-indexing are both acceptable.
This is code-golf, lowest byte-count wins.

Related: Constructible n-gons

Am I or are some of the answers misinterpreting the challenge? Aren't we simply writing a program that outputs 2^(2^n) + 1, where n is the input? This lines up with your test cases (which we know are already prime, so there's no need to check). And you don't expect the program to work where n > 4 (and n=5 is the first non-prime).

The program should theoretically function for n > 4, although that will never work in practice, as we only know of 5 Fermat primes.

I don't really understand the purpose of theoretically working for all Fermat primes, since there are only 5 known terms.

You don't appear to have responded to jstnthms's comment, and thus I still don't understand the challenge. Are we just supposed to output 2^(2^n) + 1, or is there additional work that needs to be done? Why do the answers perform additional tests?

@CodyGray The testcases are misleading, because this works for n=1:4. All fermat primes are of the form 2^2^n+1, but that does not mean that all numbers of the form 2^2^n+1 are actually prime. This is the case for n=1:4, but not for n=5 for example.

I think that some part of the confusion is that you're saying the input is n and the output must be of the form 2^(2^n)+1. If you use different variables for the input and the exponent then some confusion might be reduced. It might also help if you explicitly state that "n=5 doesn't need to output in reasonable time, but it must not output 4294967297"

Ok, I edited the question to clarify a little more.

Python 2, 53 bytes
k=input();F=2
while k:F*=F;k-=3**(F/2)%-~F/F
print-~F

Try it online!
Uses Pépin's test.

Python 2, 54 bytes
f=lambda k,F=4:k and f(k-3**(F/2)%-~F/F,F*F)or F**.5+1

Try it online!

Jelly, 13 11 bytes
ÆẸ⁺‘©ÆPµ#ṛ®

Uses 1-based indexing.
Try it online!
How it works
ÆẸ⁺‘©ÆPµ#ṛ®  Main link. No argument.

        #    Read an integer n from STDIN and call the chain to the left with
             arguments k = 0, 1, 2, ... until n matches were found.
ÆẸ           Find the integer with prime exponents [k], i.e., 2**k.
  ⁺          Repeat the previous link, yielding 2**2**k.
   ‘         Increment, yielding 2**2**k+1 and...
    ©        copy the result to the register.
     ÆP      Test the result for primality.
          ®  Yield the value from the register, i.e., the n-th Fermar prime.
         ṛ   Yield the result to the right.

Oh, so one uses ṛ to clear the result... TIL

Oh, so one uses ÆẸ instead of 2* for a single integer... TIL

Perl 6,  45  42 bytes
{({1+[**] 2,2,$++}...*).grep(*.is-prime)[$_]}

Try it
{({1+2**2**$++}...*).grep(*.is-prime)[$_]}

Try it
Expanded:
{  # bare block lambda with implicit parameter ｢$_｣

  (  # generate a sequence of the Fermat numbers

    {
      1 +
      2 ** 2 **
        $++            # value which increments each time this block is called
    }
    ...                # keep generating until:
    *                  # never stop

  ).grep(*.is-prime)\  # reject all of the non-primes
  [$_]                 # index into that sequence
}

Mathematica, 56 bytes
(t=n=0;While[t<=#,If[(PrimeQ[s=2^(2^n)+1]),t++];n++];s)&

Try it online!

Dyalog APL (29 Characters)
I'm almost certain this can be improved.
{2=+/0=(⍳|⊢)a←1+2*2*⍵:a⋄∇⍵+1}

This is a recursive function which checks the number of divisors of 1+2^2^⍵, where ⍵ is the right argument of the function. If the number of divisors is 2, the number is prime, and it returns it, otherwise, it calls the function again with ⍵+1 as a right argument.
Example
{2=+/0=(⍳|⊢)a←1+2*2*⍵:a ⋄ ∇ ⍵+1}¨⍳4
      5 17 257 65537

Here I call the function on each of ⍳4 (the numbers 1-4). It applies it to every number in turn.

Pyth, 14 bytes
e.f&P_ZsIltZQ3

Try it online!
Uses 1-indexing.

Pyth, 14 bytes
Lh^2^2byfP_yTQ

Try online.
Main idea "borrowed" from xnor's answer in another question
Lh^2^2byfP_yTQ

L                    define a function with name y and variable b, which:
 h^2^2b                returns 1+2^2^b
       y             call the recently defined function with argument:
        f    Q         the first number T >= Q (the input) for which:
         P_yT            the same function with argument T returns a prime
                     and implicitly print

05AB1E, 8 bytes
Code:
Results are 1-indexed.
µN<oo>Dp

Uses the 05AB1E encoding. Try it online!
Explanation:
µ              # Run the following n succesful times..
 N             #   Push Nn
  oo           #   Compute 2 ** (2 ** n)
    >          #   Increment by one
     D         #   Duplicate
      p        #   Check if the number is prime
               # Implicit, output the duplicated number which is on the top of the stack

Javascript, 12 46 bytes
k=>eval('for(i=n=2**2**k+1;n%--i;);1==i&&n')

Most of the code is taken up by the prime check, which is from here.

Note that it must return the nth prime Fermat number, not just the nth Fermat number.

@poi830 now the prime check takes up most of the function :(

i think you can say i<2 instead of i==1 becuase zero is also good here? that should reduce be 2 byte

Haskell, 61 bytes
p n=2^2^n;f=(!!)[p x+1|x<-[0..],all((>)2.gcd(p x+1))[2..p x]]

Try it online!
0-based index
Explanation
p n=2^2^n;                                          -- helper function
                                                    -- that computes what it says
f=                                                  -- main function
  (!!)                                              -- partially evaluate
                                                    -- index access operator
      [p x+1|                                       -- output x-th fermat number
             x<-[0..],                              -- try all fermat number indices
                      all                 [2..p x]  -- consider all numbers smaller F_x
                                                    -- if for all of them...
                         ((>)2                      -- 2 is larger than...
                              .gcd(p x+1))          -- the gcd of F_x
                                                    -- and the lambda input
                                                    -- then it is a Fermat prime!
                                                  ]

Husk, 11 bytes
!fṗmȯ→‼`^2N

Try it online!

GolfScript, 26 bytes
~3\{{(.*).,(;{*}*)1$%}do}*

Try it online!
0-indexed
~                            # Parse n to a number
 3                           # Push 3
  \{                    }*   # Execute this block n times, this block gets the next Fermat prime
    {                }do     # While the number is composite
     (.*)                    # Go to the next Fermat number
         .,(;                # Make an array from 1 to (F_n)-1
             {*}*            # Multiply the numbers to get ( (F_n)-1 )!
                 )           # Increment it
                  1$%        # This will be 0 iff the Fermat number is prime

The primality test used here is Wilson's theorem.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Float 754 to Hamming
You will be given as input an integer k in the range from -4503599627370496 (−252) to 4503599627370496 (252). As is well known, integers in this range can be represented exactly as double-precision floating-point values.
You should output the Hamming weight (number of ones) of the encoding of k in  binary64 format. This uses 1 bit for the sign, 11 bits for the exponent (encoded with an offset), and 52 for the mantissa; see the above link for details.
As an example, number 22 is represented as
0 10000000011 0110000000000000000000000000000000000000000000000000

Since there are 5 ones, the output is 5.
Note that endianness doesn't affect the result, so you can safely use your machine's actual internal representation of double-precision values to compute the output.
Additional rules

Programs or functions are allowed.
Any programming language can be used.
Standard loopholes are forbidden
The input number will be in decimal. Other than that, input/output means and format are flexible as usual.
Shortest code in bytes wins.

Test cases
22                ->   5
714               ->   6
0                 ->   0
1                 ->  10
4503599627370496  ->   5
4503599627370495  ->  55
1024              ->   3
-1024             ->   4
-4096             ->   5
1000000000        ->  16
-12345678         ->  16

Are you intending that functions can accept their inputs already in floating-point binary64 format if they want?  Some people (including myself, initially) were interpreting the question as requiring that functions accept inputs as an integer type like C's long.  In C, you can argue that the language will convert for you, just like when you call sqrt((int)foo).  But there are some x86 machine-code asm answers (like https://codegolf.stackexchange.com/a/136360/30206 and mine) which were both assuming we had to accept 64-bit integer inputs.  Accepting a binary64 value would save 5 bytes.

If so, then all that stuff about limited-range is just in case someone wanted to hack up the conversion to a binary64 bit-pattern themselves instead of type-punning?  Or for languages without type-punning?  Hmm, an interesting challenge might be to add the exponent and mantissa of a binary64 as base2 integers.  If you need to handle them separately anyway, it might be worth doing something other than type-pun and loop over all the bits.

@PeterCordes Yes, you can input in the form of a a floating-point number. The limited range is to make sure that the floating-point representation is accurate

Ok, thanks.  I guess you wanted to leave the option of writing a function that takes a long, so you couldn't just say any binary64 double, because not all doubles are integers.  But all integer-valued doubles can be converted to long and back, up to the limits of long.  (As you point out, the reverse isn't true.  You get the nearest representable double, assuming default rounding mode).  Anyway, this was a totally valid way to set up the question; I just didn't read it carefully >.<

"Note that endianness doesn't affect the result, so you can safely use your machine's actual internal representation of double-precision values to compute the output." unless your machine doesn't use IEEE floating point format...

@PeterCordes  In C++ type punning is undefined behaviour (although I think gcc usually does the Right Thing)

@JerryJeremiah: Type-punning with a union is defined in C99, and in GNU C++ as a GNU extension, so g++, clang++, and ICC all support it.  Good point about endianness; it's possible for a machine to have different float endian than integer endian, although AFAIK no modern machines are like that.  https://stackoverflow.com/q/2945174/224132.  C allows for that.  But code-golf answers only have to work on at least one implementation, not every implementation, so working on x86/gcc where double is IEEE binary64 is fine :P

Type-punning with a pointer-cast happens to work in un-optimized gcc, and sometimes works in optimized code (but is a terrible idea).  It always works with gcc -O3 -fno-strict-aliasing.  (@JerryJeremiah, I assume you were talking about type-punning the way these answers are doing it).

MATL, 5 bytes
3Z%Bz

Try it online!
Exact transliteration of my MATLAB answer. Note that input and output are implicit. -2 bytes thanks to Luis Mendo.
3Z%   % Typecast: changes input (implicitly taken and converted to double) to uint64 without changing underlying bits
B     % Convert integer to array of 1s and 0s
z     % Count nonzero entries

x86_64 machine language (Linux), 16 bytes
0:       f2 48 0f 2a c7          cvtsi2sd %rdi,  %xmm0
5:       66 48 0f 7e c0          movq     %xmm0, %rax
a:       f3 48 0f b8 c0          popcnt   %rax,  %rax
f:       c3                      retq

Accepts a single 64-bit integer parameter in RDI, converts it to a floating-point value in XMM0, stores those bits back in RAX, and then computes the hamming weight of RAX, leaving the result in RAX so it can be returned to the caller.
Requires a processor that supports the POPCNT instruction, which would be Intel Nehalem, AMD Barcelona, and later microarchitectures.
To Try it online!, compile and run the following C program:
#include<stdio.h>
const char g[]="\xF2\x48\x0F\x2A\xC7\x66\x48\x0F\x7E\xC0\xF3\x48\x0F\xB8\xC0\xC3";
#define f(x) ((int(*)(long))g)(x)

int main(int a){
  printf("%d\n",f(22));
  printf("%d\n",f(714));
  printf("%d\n",f(0));
  printf("%d\n",f(1));
  printf("%d\n",f(4503599627370496L));
  printf("%d\n",f(4503599627370495L));
  printf("%d\n",f(1024));
  printf("%d\n",f(-1024));
  printf("%d\n",f(-4096));
  printf("%d\n",f(1000000000));
  printf("%d\n",f(-12345678));
}

Edit: Fixed segfault in TIO link.

+1, the right tool for the job! This might be the only time that x86 can legitimately compete with golfing languages, or beat Jelly. :)

Ew, AT&T syntax?  You can use objdump -drwC -Mintel to disassemble in Intel syntax.  If you had a pointer in a register that you could use to store/reload, you could save bytes with movaps [rsi], xmm0 / popcnt rax, [rsi].  (movaps is only 3 bytes, 2 shorter than movq.)  But that doesn't help here, because [rsp-24] takes 2 extra bytes (SIB from using RSP as base, plus disp8).  And those extra bytes are needed in both the store and reload.  Oh well, I thought I saw a saving, but nope :/

I saved 4 bytes with a custom calling convention.  Or still save 2 bytes with the same calling convention as this, by using x87 instructions.

@DJMcMayhem: Maybe not the only time.  There are still no golfing-language answers on the Extreme Fibonacci challenge (print the first 1000 digits of Fib(1 billion), and my x86 machine code answer (105 bytes fast, or 101 bytes that runs in 5 mins instead of 1 min) is not much larger than some of the other answers, and they're all in languages with extended-precision integers built in.

Or a simpler challenge, (and without a performance requirement), chroma-key blending an array of integers.  My machine-code answer is half the length of the pyth answer.

Oh actually, the Pyth answer is a whole program.  Its chroma-key blend function is the same length (13B) as my x86-64 machine code function.  The rest of the bytes are for loading two files, applying the function, and saving a png.

C (gcc), 82 68 bytes
9 bytes thanks to Neil.
evil floating point bit level hacking
s;f(long n){double d=n;n=*(long*)&d;for(s=0;n;n*=2)s+=n<0;return s;}

Try it online!

I knew you would be the first, I just didn't expect the language :-D

@LuisMendo I just thought that it would be convenient in that language... I don't know of other languages that can do this

Save 9 bytes by shifting the other way: ...;long l=...;l*=2;)s+=l<0;...

This of course requires a C implementation with 64-bit long.  It works on x86-64 Linux, but would fail on Windows.  I'd suggest saying "gcc with 64-bit long", since gcc runs on many platforms, many of them with different ABIs.

@Peter's comment is why I added "LP64" in an edit. I also rearranged the other text in what I thought was a more logical order. I guess you didn't like that change and rolled it back, but LP64 is a standard term that describes the ABI where longs and pointers are 64-bit values (as compared to ILP64, where ints are also 64-bit, or LLP64, as used on Windows where only long longs and pointers are 64-bit and longs are still 32-bit). Maybe I should have added more explanation, or an inline link to the relevant Wikipedia article.

@CodyGray I reverted your edit because of your modification to the two lines other than LP64.

-6 bytes for n= rather than return.

Python 3, 72 71 bytes
1 byte thanks to Lynn.
lambda n:n and(bin(1020+len(bin(abs(n))))+bin(abs(n))).count('1')-(n>0)

Try it online!
Explanation
The binary64 format consists of three components:

the first bit is the sign bit, which is 1 if the number is negative
the next 11 bits store the exponent with 1023 added
the next 52 bits store the significand, or the mantissa.

n and(…)-(n>0) is a byte shorter, no?

Or int->float, or any floats at all, for that matter.

Why the abs?

C (gcc), 47 bytes
f(double n){n=__builtin_popcountl(*(long*)&n);}

This isn't portable; it was tested with gcc 7.1.1 on x86_64 running Linux, without compiler flags.
Try it online!

Input has to be an integer.  Or is it ok to let the caller handle that by implicit conversion of long to double at the call site?

Also, relying on a fluke of compiler behaviour to happen to leave n in rax with un-optimized code is pretty cheesy.  It breaks if you enable -O3, so it's not just gcc in general, it's gcc on x86-64 with 64-bit long with optimization disabled.  If you put all those requirements into your answer, I'd upvote.  I'd assume there are platforms gcc supports that have 64-bit long but that happen to leave the popcountl result in a register other than the return-value register.

I took integer in the mathematical sense. I've added the specs of my test environments, as I'm not sure that gcc, x86-64, and 64-bit longs are enough. That said, at least on x86, return-less functions work with gcc (and tcc) more often than not.

Yeah, I was just re-reading the question, and I agree that accepting the arg as a double should be fine.  It doesn't say anything about requiring the function to accept it in base2 format.  And yes, different versions of gcc could emit different code, so that's important, too.  (Fun fact: without -mpopcnt, gcc won't use the popcnt insn, and will emit a sequence of instructions to emulate it.  Some architectures don't have a popcnt instruction at all, so __builtin_popcountl always has to use some sequence of insns)

Yes, many (most?) __builtin_* functions have legacy versions to avoid generating illegal instructions. -march=native uses popcntq only if it's available.

Yeah, of course.  I just thought it was a non-obvious fun fact for people who see the highest-voted asm popcnt answer, and then another answer that looks like a C version of the same thing.  But it's totally different asm without -mpopcnt.  But yeah, that's kinda the point: use the best sequence that the target supports, instead of some pure-C idiom for the compiler to hopefully recognize.  I think the only exceptions are things like __builtin_ia32_crc32si or SSE/AVX vector builtins, which aren't declared without the corresponding -m option.  https://godbolt.org/g/H78N7S.

Java (OpenJDK 8), 92 bytes
int f(long n){int s=0;for(n=Double.doubleToLongBits((double)n);n!=0;n>>>=1)s+=n&1;return s;}

Try it online!

You can eliminate the cast and the loop. See: https://codegolf.stackexchange.com/a/136636/16413

C (gcc), 63 bytes
f(double d){long s=0,n=*(long*)&d;for(;n;n*=2)s+=n<0;return s;}

This solution is based on @LeakyNun's answer, but because he doesn't want to improve his own answer, I'm posting here more golfed version.
Try it online

I highly doubt anyone doesn't want to improve their answer.

@Mr.Xcoder. Ok, I'll keep this here until he edit his own answer. If he doesn't want to edit, this will stay here. I posted this improvement as a comment on his answer and he rejected it.

I think the input needs to be an integer type and not a real.

@ceilingcat. C implicitly converts it to double, but the input is still actualy integer.

@ThePirateBay I didn't see your comment on my answer and I'm still not seeing it now.

I put my comment and it was staying there for about a hour. In meanwhile I noticed your activity on other questions, so I concluded that you've seen my comment but rejected to improve your answer (probably because you had misunderstood the question that function should take an integer and implicitly convert to double). Also, if I spot a good improvement, what prevents me from posting it as a new answer instead of mentioning the improvement to you?

The decision to suggest improvements or post your own answer is yours, but 6 minutes is hardly about an hour.

@Dennis. Oh, so much discussion about irrelevant stuff. I've already said, if he really wants rep, I will delete this answer and let him improve his own, no problem.

C#, 81 70 68 bytes
d=>{unsafe{long l=*(long*)&d,s=0;for(;l!=0;l*=2)s-=l>>63;return s;}}

Save 11 bytes thanks to @Leaky Nun.
Saved 2 bytes thanks to @Neil.
Try it online! Uses System.BitConverter.DoubleToInt64Bits instead of the unsafe code as I couldn't get TIO to work with it.
Full/Formatted Version:
namespace System
{
    class P
    {
        static void Main()
        {
            Func<double, long> f = d =>
            {
                unsafe
                {
                    long l = *(long*)&d, s = 0;

                    for (; l != 0; l *= 2)
                        s -= l >> 63;
                    return s;
                }
            };

            Console.WriteLine(f(22));
            Console.WriteLine(f(714));
            Console.WriteLine(f(0));
            Console.WriteLine(f(1));
            Console.WriteLine(f(4503599627370496));
            Console.WriteLine(f(4503599627370495));
            Console.WriteLine(f(1024));
            Console.WriteLine(f(-1024));
            Console.WriteLine(f(-4096));
            Console.WriteLine(f(1000000000));
            Console.WriteLine(f(-12345678));

            Console.ReadLine();
        }
    }
}

for(;l!=0;l*=2) and you won't need the ternary

@LeakyNun Thanks I was scratching my head over that for ages.

Can you use s-=l>>31?

@Neil Doesn't appear to work. I assume you mean to replace s+=l<0?1:0?

My bad; l is a long, so it needs s-=l>>63?

@Neil That did the trick, thanks.

JavaScript (ES6), 81 80 77 76 bytes

f=
n=>new Uint8Array(Float64Array.of(n).buffer).map(g=i=>i&&g(i&i-1,x++),x=0)|x
<input oninput=o.textContent=f(this.value)><pre id=o>0

Edit: Saved 1 byte thanks to @Arnauld. Saved 3 bytes thanks to @DocMax. Saved 1 byte thanks to @l4m2.

Could you do g(i^i&-i,x++) for -1 byte?

@Arnauld I did wonder whether there was a golfier bit twiddle, thanks for finding it!

-3 more if you replace new Float64Array([n]) with Float64Array.of(n)

i^i&-i => i&i-1?

@l4m2 Huh, to think that it's been almost 3 years before someone spotted that golf...

Python 2, 69 bytes
-12 bytes, thanks to @ASCII-only
lambda n:bin(*unpack('Q',pack('d',n))).count('1')
from struct import*

Try it online!

71 bytes

Golfing your approach, 76 bytes,  I do recommend ASCII-only's approach though

@Mr.Xcoder the ! isn't needed since byte order doesn't matter here

69 bytes

@ASCII-only Pack the unpacked. Thanks :D

Perl 5, 33 32 + 1 (-p) = 34 33 bytes
Saved 1 byte thanks to hobbs

$_=(unpack"B*",pack d,$_)=~y/1//

Try it online!

You can save 1 byte by making d a bareword (pack d,$_ instead of pack"d",$_)

x86-64 machine code, 12 bytes for int64_t input
6 bytes for double input
Requires the popcnt ISA extension (CPUID.01H:ECX.POPCNT [Bit 23] = 1).
(Or 13 bytes if modifying the arg in-place requires writing all 64-bits, instead of leaving garbage in the upper 32.  I think it's reasonable to argue that the caller would probably only want to load the low 32b anyway, and x86 zero-extends from 32 to 64 implicitly with every 32-bit operation.
 Still, it does stop the caller from doing add rbx, [rdi] or something.)
x87 instructions are shorter than the more obvious SSE2 cvtsi2sd/movq (used in @ceilingcat's answer), and a [reg] addressing mode is the same size as a reg: just a mod/rm byte.
The trick was to come up with a way to have the value passed in memory, without needing too many bytes for addressing modes.  (e.g. passing on the stack isn't that great.)  Fortunately, the rules allow read/write args, or separate output args, so I can just get the caller to pass me a pointer to memory I'm allowed to write.
Callable from C with the signature:  void popc_double(int64_t *in_out);  Only the low 32b of the result is valid, which is maybe weird for C but natural for asm.  (Fixing this requires a REX prefix on the final store (mov [rdi], rax), so one more byte.)  On Windows, change rdi to rdx, since Windows doesn't use the x86-64 System V ABI.
NASM listing.  The TIO link has the source code without the disassembly.
  1  addr    machine      global popcnt_double_outarg
  2          code         popcnt_double_outarg:
  3                           ;; normal x86-64 ABI, or x32: void pcd(int64_t *in_out)
  4 00000000 DF2F             fild qword  [rdi]    ; int64_t -> st0
  5 00000002 DD1F             fstp qword  [rdi]    ; store binary64, using retval as scratch space.
  6 00000004 F3480FB807       popcnt rax, [rdi]
  7 00000009 8907             mov    [rdi], eax    ; update only the low 32b of the in/out arg
  8 0000000B C3               ret
    # ends at 0x0C = 12 bytes

Try it online!  Includes a _start test program that passes it a value and exits with exit status = popcnt return value.  (Open the "debug" tab to see it.)
Passing separate input/output pointers would also work (rdi and rsi in the x86-64 SystemV ABI), but then we can't reasonably destroy the 64-bit input or as easily justify needing a 64-bit output buffer while only writing the low 32b.
If we do want to argue that we can take a pointer to the input integer and destroy it, while returning output in rax, then simply omit the mov [rdi], eax from popcnt_double_outarg, bringing it down to 10 bytes.

Alternative without silly calling-convention tricks, 14 bytes
use the stack as scratch space, with push to get it there.  Use push/pop to copy registers in 2 bytes instead of 3 for mov rdi, rsp.  ([rsp] always needs a SIB byte, so it's worth spending 2 bytes to copy rsp before three instructions that use it.)
Call from C with this signature: int popcnt_double_push(int64_t);
 11                               global popcnt_double_push
 12                               popcnt_double_push:
 13 00000040 57                       push   rdi         ; put the input arg on the stack (still in binary integer format)
 14 00000041 54                       push   rsp         ; pushes the old value (rsp updates after the store).
 15 00000042 5A                       pop    rdx         ; mov      rdx, rsp
 16 00000043 DF2A                     fild   qword [rdx]
 17 00000045 DD1A                     fstp   qword [rdx]
 18 00000047 F3480FB802               popcnt rax,  [rdx]
 19 0000004C 5F                       pop    rdi         ; rebalance the stack
 20 0000004D C3                       ret
    next byte is 0x4E, so size = 14 bytes.

Accepting input in double format
The question just says it's an integer in a certain range, not that it has to be in a base2 binary integer representation.  Accepting double input means there's no point in using x87 anymore.  (Unless you use a custom calling convention where doubles are passed in x87 registers.  Then store to the red-zone below the stack, and popcnt from there.)
11 bytes:
 57 00000110 66480F7EC0               movq    rax, xmm0
 58 00000115 F3480FB8C0               popcnt  rax, rax
 59 0000011A C3                       ret

But we can use the same pass-by-reference trick as before to make a 6-byte version: int pcd(const double&d);
 58 00000110 F3480FB807               popcnt  rax, [rdi]
 59 00000115 C3                       ret

6 bytes.

MATLAB, 36 bytes
@(n)nnz(de2bi(typecast(n,'uint64')))

Using the fact that de2bi is not only shorter than dec2bin, but also provides a result in ones and zeroes rather than ASCII 48, 49.

Java (64, 61, 41 bytes)
Completely straightforward using the standard library (Java SE 5+):
int f(long n){return Long.bitCount(Double.doubleToLongBits(n));}
Contribution by Kevin Cruijssen (Java SE 5+):
int f(Long n){return n.bitCount(Double.doubleToLongBits(n));}

Contribution by Kevin Cruijssen (Java SE 8+, lambda function):
n->n.bitCount(Double.doubleToLongBits(n))

Nicely done! :-)

Nice answer, +1 from me. You can golf three bytes by taking the parameter as Long n and use n.bitCount(...) instead of Long.bitCount(...). In addition, if you use Java 8+, you can golf it to n->n.bitCount(Double.doubleToLongBits(n)) (41 bytes)

JavaScript (Node.js), 7976 bytes
n=>n&&((g=n=>t=n.toString(2))(n)+g(t.length*2-(n<0)+2044)).split`1`.length-2

Try it online!
First answer not relying on cast? At least this is earlier

Just to try a different, safer-than-TheLethalCoder's approach, I came up with this (it's a pity C# has such long method names):
C# (.NET Core), 76+13 bytes
d=>Convert.ToString(BitConverter.DoubleToInt64Bits(d),2).Split('1').Length-1

Try it online!
Byte count includes 13 bytes for using System;. First I need to convert the double to a long that has the same binary representation, then I can convert it to a binary string, and then I count the 1s just by splitting the string and counting the substrings minus 1.

Nice alternative but you need to include the using into your byte count.

Use Linq for 95 bytes only a few more: namespace System.Linq;{d=>Convert.ToString(BitConverter.DoubleToInt64Bits(d),2).Count(c=>c>48)}. Though I haven't tested it, it should work.

@TheLethalCoder it works, but I tried to avoid Linq so I didn't have to add a second using directive.

When you add the second that's when namespaces come in handy. But yeah in this case avoiding Linq was slightly cheaper. Just wanted to comment with it's approach in case you had any ideas on how to shorten it to save you bytes.

@TheLethalCoder, Sum(c=>c&1) is shorter. Or Sum()-768

@PeterTaylor True, either way it appears to be longer still.

Jelly, 19 bytes
AB©L+⁽¡ßB;®ċ1_>0$a@

Try it online!

Erlang 55 bytes
fun(X)->length([Y||<<Y:1>><=<<X:64/float>>,Y=:=1])end.

An anonymous function that counts all the 1s in a number encoded as a 64 bit float.
references:

http://erlang.org/doc/programming_examples/bit_syntax.html
http://erlang.org/doc/programming_examples/list_comprehensions.html

dc, 79 bytes
[pq]su[-1r]st0dsb?dd0=u0>tsa[1+]ss[la2%1=slb1+sblad2/sa1<r]dsrxlb1022+sa0lrx+1-

Output is left on top of the stack.
I'll add an explanation later.
Try it online!
Note that negative numbers are preceded by _, not -.

Groovy (with Parrot parser), 46 bytes
f=n->Long.bitCount(Double.doubleToLongBits(n))

C, 67 bytes
int i;g(char*v){int j=v[i/8]&1<<i%8;return!!j+(++i<64?g(v):(i=0));}

control code and results
#define R     return
#define u32 unsigned
#define F        for
#define P     printf

int main()
{/*           5   6 0 10                5               55    3      4       16*/
 double v[]={22,714,0,1 ,4503599627370496,4503599627370495,1024, -1024, -12345678};
 int i;

 F(i=0;i<9;++i)
     P("%f = %d\n", v[i], g(&v[i]));
 R 0;
}

>tri4
22.000000 = 5
714.000000 = 6
0.000000 = 0
1.000000 = 10
4503599627370496.000000 = 5
4503599627370495.000000 = 55
1024.000000 = 3
-1024.000000 = 4
-12345678.000000 = 16

Husk, 20 bytes
&->0±¹ΣS+ȯḋ+1022Lḋa¹

Try it online! A port of Leaky Nun's Python 3 answer.

05AB1E, 17 bytes
ĀiÄbDgŽ42+b«1¢Id-

Port of @LeakyNun's Python 3 answer, so make sure to upvote him as well!
Try it online or verify all test cases.
Explanation:
Āi                 # If the (implicit) input-integer is NOT 0:
  Ä                #  Take the absolute value of the (implicit) input-integer
   b               #  Convert it to binary
    Dg             #  Duplicate it, then pop and push its length
      Ž42+         #  Add compressed integer 1022 to this length
          b        #  Convert it to binary as well
           «       #  Merge the two binary-strings together
            1¢     #  Count the amount of 1s in this string
              Id   #  Check that the input-integer is non-negative (1 if >=0; 0 if <0)
                -  #  Subtract that from the count
                   #  (after which it is output implicitly as result)
                   # (implicit else: output the implicit input, which is 0)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why Ž42 is 1022.

Rust, 27 bytes
|n|n.to_bits().count_ones()

Try it online!
An anonymous function that takes in an f64 and outputs a u32. The to_bits function reinterprets the bits of an f64 into a u64, where I can use the convenient count_ones function to trivialize the problem.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Skip like a rabbit!
Given a list of non-negative integers in any reasonable format, iterate over it, skipping as many elements as every integer you step on says.

Here is a worked example:
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | []
 ^ First element, always include it
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0]
    ^ Skip 0 elements
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1]
          ^ Skip 1 element
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1, 2]
                   ^ Skip 2 elements
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2] | [0, 1, 2, 3]
Skip 3 elements; you're done

Another worked example, not so all-equal-deltas:
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | []
 ^ First element, always include it
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4]
                ^ Skip 4 elements
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3]
                            ^ Skip 3 elements
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3, 3]
                                        ^ Skip 3 elements
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] | [4, 3, 3, 4]
Skip 4 elements; you're done

An out-of-bounds example:
[0, 2, 0, 2, 4, 1, 2] | []
^ First element, always include it
[0, 2, 0, 2, 4, 1, 2] | [0]
    ^ Skip 0 elements
[0, 2, 0, 2, 4, 1, 2] | [0, 2]
             ^ Skip 2 elements
[0, 2, 0, 2, 4, 1, 2] | [0, 2, 4]
Skip 4 elements; you're done (out of bounds)

Rules

You may not use any boring cheat among these ones, they make the challenge boring and uninteresting.
You should only return/print the final result. STDERR output is ignored.
You may not get the input as a string of digits in any base (e.g. "0102513162" for the first case).
You must use left-to-right order for input.
As in the worked examples, if you go out of bounds, execution terminates as if otherwise.
You should use 0 for skipping 0 elements.
Given the empty list ([]) as input, you should return [].

Test cases
[]                                                     => []
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                     => [0, 1, 3, 7]
[5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0]                   => [5, 2, 1, 0]
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2]                         => [0, 1, 2, 3]
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] => [4, 3, 3, 4]
[0, 2, 0, 2, 4, 1, 2]                                  => [0, 2, 4]

This is code-golf, so shortest answer wins!

Is it okay to have trailing zeros in my array? would save me ~18 bytes

@EriktheOutgolfer Could we output a string array and have trailing empty strings?

@TheLethalCoder Sorry I'd say no since that's not reasonable imo...can't you just remove trailing ""s?

@RomanGräf Sorry but no, that would be too ambiguous since there are cases you should have trailing 0s in the output.

Python 2, 36 bytes
f=lambda x:x and x[:1]+f(x[x[0]+1:])

Try it online!

I was expecting to get outgolfed, but not that badly :)

Can't you do x[0] instead of x[:1]?

@EriktheOutgolfer yes, but it need to be a list, so it would be [x[0]]

@Rod You're not saving any bytes with x[:1] anyways...f=lambda x:x and[x[0]]+f(x[x[0]+1:])

Python 2, 49 44* 41 bytes
Crossed out 44 is still regular 44 :(
* -3 thanks to @ASCII-only.
l=input()
while l:print l[0];l=l[l[0]+1:]

Try it online!
Prints the results separated by a newline, as the OP allowed in chat. I don't think it can get any shorter as a non-recursive full program.

How does this work?

l=input() - Reads the list from the standard input.

while l: - Abuses the fact that empty lists are falsy in Python, loops until the list is empty.

print l[0]; - Prints the first element of the list.

l=l[l[0]+1:] - "Skips like a rabbit" - Trims the first l[0]+1 from the list.

Let's take an example
Given the list [5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0] as input, the code performs the following (according to the explanation above) - Prints the first item of the array: 5, trim the first 6: [2, 1, 2, 1, 0, 0]. We then print 2 and trim the first 3: [1,0,0]. Likewise, we output 1, crop the first 2, and we get [0]. Of course, 0 is printed and the program terminates.

46 bytes

Haskell, 29 27 26 bytes
j(x:y)=x:j(drop x y)
j x=x

Saved 1 byte thanks to Zgarb.
Try it online.

f x=x on the second line saves a byte.

JavaScript (ES6), 42 39 35 bytes
a=>a.map((n,i)=>a.splice(i+1,n))&&a

let f =
a=>a.map((n,i)=>a.splice(i+1,n))&&a

console.log(f([]))                                                     // => []
console.log(f([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))                     // => [0, 1, 3, 7]
console.log(f([5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0]))                   // => [5, 2, 1, 0]
console.log(f([0, 1, 0, 2, 5, 1, 3, 1, 6, 2]))                         // => [0, 1, 2, 3]
console.log(f([4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2])) // => [4, 3, 3, 4]
console.log(f([0, 2, 0, 2, 4, 1, 2]))                                  // => [0, 2, 4]

Old Solution 39 Bytes
a=>a.map(n=>i--||r.push(i=n),r=i=[])&&r

-3 bytes thanks to @ThePirateBay

39 bytes a=>a.map(n=>i--||r.push(i=n),r=i=[])&&r

05AB1E, 10 9 bytes
[¬Dg>#=ƒ¦

Uses the 05AB1E encoding. Try it online!

Yeah, that is way better than what I was thinking.

Mathematica, 46 44 bytes
SequenceCases[#,{x_,y___}/;Tr[1^{y}]<=x:>x]&

Alternatives:
SequenceCases[#,{x_,y___}/;x>=Length@!y:>x]&
SequenceCases[#,l:{x_,___}/;x>Tr[1^l]-2:>x]&

C#, 68 bytes
a=>{for(int i=0;i<a.Count;i+=a[i]+1)System.Console.Write(a[i]+" ");}

Try it online!
Full/Formatted version:
namespace System
{
    class P
    {
        static void Main()
        {
            Action<Collections.Generic.List<int>> f = a =>
            {
                for (int i = 0; i < a.Count; i += a[i] + 1)
                    System.Console.Write(a[i] + " ");
            };

            f(new Collections.Generic.List<int>() { });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0 });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 0, 1, 0, 2, 5, 1, 3, 1, 6, 2 });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2 });Console.WriteLine();
            f(new Collections.Generic.List<int>() { 0, 2, 0, 2, 4, 1, 2 });Console.WriteLine();

            Console.ReadLine();
        }
    }
}

Returning a list is longer at 107 bytes.
a=>{var l=new System.Collections.Generic.List<int>();for(int i=0;i<a.Count;i+=a[i]+1)l.Add(a[i]);return l;}

Why has someone downvoted this?

To round your score and make a perfect 5k?

@ThomasAyoub We can only assume it was someone with OCD yes.

Husk, 8 6 bytes
←TU¡Γ↓

Try it online!
-2 bytes (and a completely new solution idea) thanks to Leo!
Explanation
I'm using the list pattern match function Γ.
It takes a function f and a list with head x and tail xs, and applies f to x and xs.
If the list is empty, Γ returns a default value consistent with its type, in this case an empty list.
We take f to be ↓, which drops x elements from xs.
This function is then iterated and the resulting elements are collected in a list.
←TU¡Γ↓  Implicit input, e.g. [0,2,0,2,4,1,2]
    Γ↓  Pattern match using drop
   ¡    iterated infinitely: [[0,2,0,2,4,1,2],[2,0,2,4,1,2],[4,1,2],[],[],[],...
  U     Cut at first repeated value: [[0,2,0,2,4,1,2],[2,0,2,4,1,2],[4,1,2],[]]
 T      Transpose: [[0,2,4],[2,0,1],[0,2,2],[2,4],[4,1],[1,2],[2]]
←       First element: [0,2,4]

You can drop the default value of ø, and everything will still magically work :)

Or, for even less bytes, https://tio.run/##yygtzv7//1HbhJDQQwvPTX7UNvn////RBjpGOiBsomOoYxQLAA

@Leo Oh wow, that's clever!

Why did you CW this?

@ErikTheOutgolfer That was a mistake (I'm on my phone and apparently pushed something by accident). I'm trying to undo it...

@Zgarb You must flag it for mod attention...flagged it too.

Python 2, 59 55 bytes
l=input()
i=0
while l[i:]:i+=1;l[i:i+l[i-1]]=[]
print l

Try it online!

You can use l[i:i+l[i-1]]=[] instead del l[i:i+l[i-1]] to save a byte

56 bytes

Pyth, 22 Bytes
VQ aY.(Q0VeY .x.(Q0 ;Y

Removed a useless byte

I see 23 bytes there.

Typo :) sorry...

I'm not sure why you have a down vote.  There is a possibility that when you edited fixing your answer this triggered an "automatic down vote".  The reasons for this automatic downvote are confusing and terrible but it happens if the system considers your answer to be "low quality" based on it heuristics.  Its also possible that someone didn't like your answer, but I don't see anything wrong with it at the moment so I'm not sure why that would be the case.

I'm glad you're using Pyth!

Python 2, 60 42 41 bytes
-18 bytes thanks to Luis Mendo
-1 byte thanks to Jonathan Frech

x=input()
i=0
while 1:print x[i];i-=~x[i]

Try it online!

i-=~x[i] is one byte shorter than i+=1+x[i].

Retina, 36 bytes
Byte count assumes ISO 8859-1 encoding.
.+
$*
((1)*¶)(?<-2>1*¶)*
$1
%M`.
0$

Input and output are linefeed-separated with a trailing linefeed.
Try it online! (Uses commas instead of linefeeds to allow for convenient test suites.)

Brain-Flak, 64 bytes
([]){{}(({})<>)<>{({}[()]<{}>)}{}([])}{}<>([]){{}({}<>)<>([])}<>

Try it online!
([]){{}                          ([])}{}                         # Until the stack is empty
       (({})<>)<>                                                # Copy TOS to off stack
                 {({}[()]<{}>)}{}                                # Pop TOS times
                                        <>([]){{}({}<>)<>([])}<> # Reverse off stack

Holy crap! I wrote up a solution, and then scrolled down to post it, but it turns out we wrote the exact same solution byte-for-byte! Even minor details like ({}[()]<{}>) vs ({}<{}>[()]) were the same! What a coincidence!

@DJMcMayhem stealing all the fame XD

I also made a byte for byte identical solution, but I golfed it down 4 bytes.  Just some delayed competition :)

Mathematica, 64 50 bytes
±x_List:=Prepend[±Drop[x,1+#&@@x],#&@@x]
±_=±{}={}

I couldn't resist further golfing this neat code; my answer is below.

Java (OpenJDK 8), 53 bytes
Thanks to @PunPun1000 and @TheLethalCoder
a->{for(int n=0;;n+=1+a[n])System.out.println(a[n]);}

Try it online!

Would printing the results, like in my C# answer, save you anything?

@TheLethalCoder Ill try

Can you save a byte by moving n into the loop?

Plus this doesn't seem to work at the moment.

You're missing a paren after the (a[n+=1+a[n]].  Function also throws an error after outputting the correct value, I don't know the concensus on whether this is allowed or not (the question does say anything to standard error is ignore).  If that was the intention, then you can remove the n<a.length in the for loop.  Finally the TIO code doesn't run as is, even with the paren.  The function should be a Consumer<int[]> and use func.accept(test)

It looks like it's ok to error out, in that case I definitely recommend removing the n<a.length in the for loop: TIO (52 bytes)

@PunPun1000 your solution skips the first element so i moved n+=... in the for header for an extra byte

You can use n-=~a[n] to save 1 byte.

R, 58 bytes
f=function(x,p=1){cat(z<-x[p]);if(p+z<sum(x|1))f(x,p+z+1)}

Recursive function. Takes a vector x as argument and intiates a pointer p. This prints the corresponding entry of x, checks if p+x[p] would go out of bounds, and if not, calls the function for the new pointer.
f=function(x,p=1,s=x[1])`if`((z<-x[p]+p+1)>sum(x|1),s,f(x,z,c(s,x[z])))

This is a comparable solution that returns a proper vector instead of printing the digits.

what about an input of numeric(0)? aka empty array.

@Giuseppe I'll take a look at it when I'm behind my pc

55 bytes

C# (.NET Core), 68 bytes
n=>{var t="";for(int i=0;i<n.Length;i+=n[i]+1)t+=n[i]+" ";return t;}

Try it online!
Takes input as an array of integers, returns a string containing the non-skipped values.

Nice way to do it and comes in at the same count as printing.

I love the simple solutions. Still gotta learn LINQ though, as I have seen that shorten so many c# lambdas..

Shortens it because you can implicit return most of the time. Though it is a toss up between implicit return with using System.Linq; and a normal loop.

Alice, 15 bytes
/$.. \h&
\I@nO/

Try it online!
Input and output a linefeed-separated lists of decimal integers.
Explanation
/   Switch to Ordinal mode.
I   Read a line.
.   Duplicate it.
n   Logical NOT (gives truthy if we're at EOF).
/   Switch to Cardinal.
    The IP wraps around to the left.
\   Switch to Ordinal.
$@  Terminate the program if we're at EOF.
.   Duplicate the input line again.
O   Print it.
\   Switch to Cardinal.
h   Increment the value.
&   Store the result in the iterator queue.
    The program wraps around to the beginning.

Storing an integer n in the iterator queue causes the next command to be executed n times. Mirrors like / are not commands, so the next command will be I. Therefore if we just read and printed a value x, we will read x+1 values on the next iteration, with the last of them ending up on top of the stack. This skips the required number list elements.

Mathematica, 37 (30?)
Further golfing of user202729's fine method.
±{a_,x___}={a}~Join~±{x}~Drop~a
±_={}

The rules don't seem to explicitly specify the output format, so maybe:
±{a_,x___}=a.±{x}~Drop~a
±_={}

Output for the second function looks like: 0.2.4.{} — notably {} is still returned for an empty set, conforming to the final rule.

±Drop[{x},a] can be ±{x}~Drop~a because ± has a lower precedence than Infix.

@JungHwanMin I missed that; thanks!

Common Lisp, 51 bytes
(do((x(read)(nthcdr(1+(print(car x)))x)))((not x)))

Try it online!

Brain-Flak, 64 60 bytes
4 bytes save based on an idea from 0 '
([]){{}(({})<>())<>{({}[()]<{}>)}{}([])}{}<>{({}[()]<>)<>}<>

Try it online!
Annotated
([]){{}            #{Until the stack is empty}
  (({})<>())<>     #{Put n+1 to the offstack}
  {({}[()]<{}>)}{} #{Remove n items from the top}
([])}{}            #{End until}
<>                 #{Swap stacks}
{({}[()]<>)<>}<>   #{Move everything back onto the left stack decrementing by 1}

Python 2.4, 85 bytes
No chance to win in python with it, but I love oneliners and this one might be interesting to others.
Turns out, there is a fancy magic trick to access building list inside comprehension, but it works only in 2.4 and with some edits in <= 2.3
locals()['_[1]'] it is.
Python creates secret name _[1] for list, while it is created and store it in locals. Also names _[2], _[3]... are used for nested lists.
lambda n:[j for i,j in enumerate(n)if i==len(locals()['_[1]'])+sum(locals()['_[1]'])]

So it counts number of already added elements plus their sum. Result is the index of next desired element.
I think, that there should be a way to avoid enumerate. Like accessing input array directly by index: [ n[len(locals()['_[1]'])+sum(locals()['_[1]'])] for ... ]. But I can't figure out a compact way to protect it from index-out-of-range (while keeping it oneliner)

Ruby, 36 33 31
f=->l{a,*l=l;a&&f[l.drop(p a)]}

Try it online.

You're allowed to subtract the f= as a header element.

@sethrin Even if I need to call it recursively?

Hmm, good question. I suppose not. I did very much like that about your solution, by the way.

Swift, 63 bytes
func a(d:[Int]){var i=0;while i<d.count{print(d[i]);i+=d[i]+1}}

This is my first entry, ever, so I'm not 100% sure on the rules, but hopefully this answer suffices. I'm a little unsure of rules on how to get the input into a system. I have a shorter answer if I was allowed to assume a function somewhere that can return the input.

Welcome to PPCG! The default rules are that you can either have code that works as a full program, so input (usually) in STDIN and output (usually) to STDOUT, or a function, so input (usually) from function parameters and output (usually) from function return.

@StepHen - thanks! I guess that makes my other version invalid then. Looking forward to contributing more!

Perl 5, 36 30 + 1 (-a) = 31 bytes
$i+=$F[$i]+say$F[$i]while$i<@F

Try it online!
Takes its input as a space separated list of numbers.

Perl 6, 31 bytes
{(@_,{.[1+.[0]..*]}...^0)[*;0]}

Test it
Expanded:
{  # bare block lambda with implicit parameter ｢@_｣
  (
    # generate a sequence

    @_,

    {
      .[ # index into previous value in the sequence
        1 + .[0]  # start by skipping one plus the first element
                  # of the previous value in the sequence
        ..  *     # use that to create a Range with no end
      ]
    }

    ...^  # keep doing that until: (and throw away last value)
    0     # it generates an empty list

  )[ *; 0 ]  # from every value in the sequence, get the first element
}

To help understand how the code works, without [*;0] this would generate a sequence like the following:
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2],
   (1, 0, 2, 5, 1, 3, 1, 6, 2),
         (2, 5, 1, 3, 1, 6, 2),
                  (3, 1, 6, 2)

Python 3, 35 bytes
f=lambda h=0,*t:t and[h,*f(*t[h:])]

Try it online!
Run it with f(*l) where l is your input. Arguably stretching the rules for input, but I just love advanced unpacking.

C++ (gcc), 172 bytes
(for 144 bytes see @ceilingcat comment)
#include<iostream>
int main(){std::istream& i=std::cin;char c;int a,b;while(i>>c&&i>>a){std::cout<<c<<(c/91?"":" ")<<a;while(a--&&i>>c&&i>>b);}std::cout<<c<<(c/93?"":"]");}

Try it online
The awful (c/91?"":" ") is for correct spacing in output. Without it (-15 bytes) output is in form: [0,2,4], when I change it to simple " " (-9 bytes) output is like [ 0, 2, 4] (additional space at the beginning).
<<(c/93?"":"]") on the end is only to handle [] empty input corner case
Prints no trailing endline.

You can also print the numbers separated by a no-digit separator, no need for [] and you can have empty output for that edge-case, and no need for (c/91?"":" "). You don't have to match the format of the examples in the challenge.

144 bytes

@ceilingcat so when I looked at my answer after this two years, changing std:istream to auto was the first thing I thought about. Thanks!

Jelly, 8 bytes
ḢṄ‘ṫ@µL¿

A full program printing the results each followed by a newline (empty list produces no output).
Try it online!
How?
ḢṄ‘ṫ@µL¿ - Main link: list of non-negative integers  e.g. [2,5,4,0,1,2,0]
       ¿ - while:           Iteration:  1                  2             3          4        5
      L  -   length (0 is falsey)       7                  4             3          1        0
     µ   - ...do:                                                                            stop
Ḣ        -   head (pop & modify)        2 ([5,4,0,1,2,0])  0 ([1,2,0])   1 ([2,0])  0 ([0])
 Ṅ       -   print it (and yield it)   "2\n"              "0\n"         "1\n"      "0\n"
  ‘      -   increment                  3                  1             2          1
   ṫ@    -   tail from index            [0,1,2,0]          [1,2,0]      [0]         []
         -
         -                       i.e. a resulting in the printing of: '''2
                                                                         0
                                                                         1
                                                                         0
                                                                         '''

Finally a Jelly answer! BTW I can do it in 7 bytes.

And I also have a list-returning function in 18 bytes.

APL (Dyalog Unicode), 20 bytesSBCS
{⍵≡⍬:⍬⋄(⊃,∘∇1↓⊃↓⊢)⍵}

Try it online!

The way you use that tacit function inside the dfn is creative.

PowerShell, 25 bytes
$args|?{!$s--}|%{($s=$_)}

Try it online!

Mathematica, 65 bytes
(s=#;t=1;w={};While[t<=Length@s,AppendTo[w,k=s[[t]]];t=t+k+1];w)&

Try it online!

Clojure, 67 bytes
#(nth(reduce(fn[[z k]b](if(= z 0)[b(conj k b)][(- z 1)k]))[0[]]%)1)

Starts with the initial parameters [0 []], where 0 is the counter and [] is the result. If the first element in this list is 0 appends item n from the argument to the result and passes further this list [n [... n]] otherwise decrements the first element. (this explanation feels horrible to me)
See it online

Batch, 69 bytes
:l
@if not "%1"=="" echo %1&(for /l %%i in (0,1,%1)do @shift)&goto l

(I need the ()s around the for otherwise the goto happens inside the loop.)

C (gcc), 100 96 93 90 65 61 58 bytes
s;main(d){while(scanf("%d",&d)>0)s--||printf("%d\n",s=d);}

Try it online!

recursive main() saves a few bytes, yay!
indexing into string saves another 3 bytes
relaxing the output format saves a whole lot of bytes (25 to be exact), see here the shortest version with nice list-style output (90 bytes):
s;d;main(p){scanf("%*c %d",&d)>0?s--||printf(p?"[%d":", %d",s=d),main(0):printf("[]"+!p);}

a different input format (1 number per line) saves another 4 bytes
Now it's shorter without recursion

Suggest ~scanf("%d",&d) instead of scanf("%d",&d)>0

Perl 6, 33 bytes
my&f={$_&&(.[0],|f .[.[0]+1..*])}

Try it online!

Cubix, 24 bytes
U.;@I)!/(O?vL!(.;I<.oWSL

Try it online!
Takes input as a comma- (or whitespace-) separated list with a -1 at the end to signify end of input.
I expect there's some golfing to do here.
Expands to the following cube:
    U .
    ; @
I ) ! / ( O ? v
L ! ( . ; I < .
    o W
    S L

Algorithm is in two parts:

I) : read in an input, increment it.
!/ : If zero (i.e., input is -1), turn left to @ and end program, otherwise proceed
(O : decrement and output as a number
?  : if zero, go straight, if positive, turn right.

Positive case:

<I : go right and read in input
;( : pop TOS and decrement TOS
!L : skip L (turn left) if TOS is nonzero
wrap around to <I again
otherwise we hit SLWo(!;U which is the same as the zero case.

Zero case:

vS : go down, push 32 (space character)
o( : output as a character, decrement
!; : (no ops)
U  : re-enter main loop, I)!/ etc.

Jelly, 7 bytes
ḊḢṄ$¡¹¿

Try it online!
Since nobody has discovered this yet (I challenged Jonathan Allan a long time ago), I am posting it.
Jelly, 12 bytes
Ḋ1ị$‘$¡ÐĿṖḢ€

Try it online!
I had 18 bytes back then (can't remember the exact code), but now I managed to make a list-returning version in 12 bytes.

PHP, 74 bytes
function s($l){$k=0;while(isset($l[$k]))$k+=($r[]=$l[$k])+1;return$r?:[];}

Try it online!

PowerShell, 57 50 bytes
-7 bytes thanks to mazzy
param($l)for(;$i-lt$l.count){($z=$l[$i++]);$i+=$z}

Try it online!
Simple for-loop approach that does alright.

50 bytes?

Japt, 5 bytes
Modifies the input array in place.
£jYÄX

Try it - Footer outputs the original array

Javascript 2019, 43 42 chars
a=>a.flatMap(x=>i^q++?[]:(i+=x+1,x),i=q=0)

Test:

f=a=>a.flatMap(x=>i^q++?[]:(i+=x+1,x),i=q=0)

console.log(
`[]                                                    => []
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                     => [0, 1, 3, 7]
[5, 1, 2, 3, 4, 5, 2, 1, 2, 1, 0, 0]                   => [5, 2, 1, 0]
[0, 1, 0, 2, 5, 1, 3, 1, 6, 2]                         => [0, 1, 2, 3]
[4, 5, 1, 3, 8, 3, 0, 1, 1, 3, 1, 2, 7, 4, 0, 0, 1, 2] => [4, 3, 3, 4]
[0, 2, 0, 2, 4, 1, 2]                                  => [0, 2, 4]`
.split`
`.map(s=>s.split`=>`)
.map(([s,key])=>f(eval(s))==""+eval(key))
)

Runic Enchantments, 25 bytes
>Ri:$' $\
~/i~1-!;R:0)2*?

Try it online!
But input and output are space-separated integer lists. There is a trailing space because the logic to check to see if any input was actually read is a pain (and about 7 bytes) and not strictly needed for processing of this sort.

Stax, 5 bytes
√⌡╜9{

Run and debug it

PHP, 66 bytes
function($a){for(;$x<count($a);$x+=$o[]=$a[$x++|0]);return$o?:[];}

Try it online!
Output:
[]                                       => []
[0,1,2,3,4,5,6,7,8,9,10]                 => [0,1,3,7]
[5,1,2,3,4,5,2,1,2,1,0,0]                => [5,2,1,0]
[0,1,0,2,5,1,3,1,6,2]                    => [0,1,2,3]
[4,5,1,3,8,3,0,1,1,3,1,2,7,4,0,0,1,2]    => [4,3,3,4]
[0,2,0,2,4,1,2]                          => [0,2,4]


text:
How Cloudy Is It?
Challenge
Given an image of the sky, you must output the cloud cover in oktas. The image supplied will be an image file (the type is up to you) and the output should be to STDOUT.
Oktas
In meteorology, an okta is a unit of measurement used to describe the amount of cloud cover at any given location such as a weather station. Sky conditions are estimated in terms of how many eighths of the sky are covered in cloud, ranging from 0 oktas (completely clear sky) through to 8 oktas (completely overcast).
The sky will always be a picture from around midday (so, blue sky, not red/night sky).
The colour of a cloud will always be a colour which follows the following pattern:
#ABCDEF

Where AB >= C0, CD >= C0 and EF >= C0.
Or, in RGB:
(A, B, C)

Where A >= 192, B >= 192 and C >= 192.
Here are the percentage coverages related to the oktas:
0%    - 0 oktas
12.5% - 1 okta
25%   - 2 oktas
37.5% - 3 oktas
50%   - 4 oktas
62.5% - 5 oktas
75%   - 6 oktas
87.5% - 7 oktas
100%  - 8 oktas

The percentages are the percentage of the image which is cloud.
If you the percentage cloud of your image is not a multiple of 12.5, you should round to the nearest.
Output
The output should just be the okta number (you don't have to say the unit).
Examples
1 okta (18.030743615677714% cloud)

0 oktas (0.0% cloud)

3 oktas (42.66319444444445% cloud)

(source: hswstatic.com)
1 okta (12.000401814778645% cloud)

Python code used to calculate numbers
Winning
Shortest code in bytes wins.

Isn't the last one 3 oktas?

@TheLethalCoder Whoops, edited

Is there a maximum to the dimensions of an image?

@Shaggy Not really. As large as your language can handle

I've added a 4th test case that requires rounding up to 12.5, since answers using integer flooring would've been passing the first 3 test cases.

@JustinMariner Good call :D

About languages that don't have image processing capabilities like C++, is it ok to use a library ? If so, for the byte count, should it count only the written code or also the size of DLL files required to run the program ?

@HatsuPointerKun Yeah, that's allowed like how Pythoj uses PIL

@Hatsu It's only the byte count of the driver program that counts. So, in C++, you would need at least one #include directive, and that would be included in your byte count. But not the byte count of the library code. (I'm not sure about build flags that control linking to the library. I could argue either way, and I can't find a community consensus about this. Low-level languages don't get a lot of love around here, in my opinion. :-()

MATL, 18 17 bytes
Yi191>3&A1eYm8*Yo

Example runs with the four provided images (sorry about preview quality; click for full resolution):

Or remove the last four characters to see the results without rounding:

Explanation
Yi     % Implicitly input filename or URL. Read image. Gives an M×N×3 array
191>   % Does each entry exceed 191?
3&A    % True for 3rd-dim "lines" that only contain true. Gives an M×N matrix
1e     % Linearize (flatten) into a 1×L row vector, with L = M*N
Ym     % Mean of vector
8*     % Multiply by 8
Yo     % Round. Implicitly display

I wonder what can be done using esolangs

Python 2, 114 110 98 bytes
-4 bytes thanks to TheLethalCoder
-12 bytes thanks to Ruud

import PIL.Image as P
i=P.open(input()).getdata()
print round(8.*sum(min(x)>191for x in i)/len(i))

Try it online!

Use 191 instead?

I was going to suggest x&y&z&192>191, but the updated version is just as short.

98 bytes

Could you potentially replace import PIL.Image as P with from PIL.Image import* and save 1 byte when changing i=P.open to i=open?  I don't know if that'd cause problems since open is already a defined function, but I can't test since I don't have the ability to install the module.

Yeah, that seems to work. Saves 1 byte.

@ArnoldPalmer PIL won't allow import* on some plataforms

@Rod your code doesn’t have to run on all platforms - the language is defined by the interpreter. If it runs for you then it’s valid.

Java (OpenJDK 8), 204 bytes
i->{int x=0,y=0,t=0,w=i.getWidth(),h=i.getHeight();for(;x<w;)for(y=0;y<h;){java.awt.Color c=new java.awt.Color(i.getRGB(x++,y++));if(c.getRed()>191&&c.getBlue()>191&&c.getGreen()>191)t++;}return 8*t/w/h;}

Try it online! I always forget that TIO outputs STDERR to the debug tab.. Maybe it could like highlight red in case of an error?

Few things: your code currently runs in an infinite loop, since you never increment x or y. You assigned y=0 twice, so you can remove the first assignment. The class Color must be either fully-qualified (java.awt.Color) or you must include the import in your byte count. And your code fails for the 4th test case (returns 0 instead of 1).

I know it's been a while, but you can golf 6 bytes by removing the brackets of the inner for-loop, and changing the && to & and ,y=0 to ,y: Try it online.

C#, 150 146 bytes
b=>{int t=0,c=0,w=0,h;for(;w<b.Width;++w)for(h=0;h<b.Height;++t){var p=b.GetPixel(w,h++);if(p.R>191&p.G>191&p.B>191)c++;}return(int)(c/(t+0d)*8);}

Saved 4 bytes thanks to @Ian H.
Full/Formatted version:
using System.Drawing;

namespace System
{
    class P
    {
        static void Main()
        {
            Func<Bitmap, int> f = b =>
            {
                int t = 0, c = 0, w = 0, h;
                for (; w < b.Width; ++w)
                    for (h = 0; h < b.Height; ++t)
                    {
                        var p = b.GetPixel(w, h++);

                        if (p.R > 191 & p.G > 191 & p.B > 191)
                            c++;
                    }

                return (int)(c / (t + 0d) * 8);
            };

            string[] testCases =
            {
                @"Appearance_of_sky_for_weather_forecast,_Dhaka,_Bangladesh.JPG",
                @"spanish-sky.jpeg",
                @"why-is-sky-blue-1.jpg",
            };

            foreach (string testCase in testCases)
            {
                using (Bitmap bitmap = new Bitmap(testCase))
                {
                    Console.WriteLine(f(bitmap));
                }
            }

            Console.ReadLine();
        }
    }
}

for(h=0 h<b.Height;++t) I think you missed a semi-colon there

You can replace the /0.125 with *8 at the end to save a few bytes.

@Cowsquack I'd deleted the semi colon instead of the space! Fixed now..

PowerShell, 200 bytes
$a=New-Object System.Drawing.Bitmap $args[0]
0..($a.Height-1)|%{$h=$_;0..($a.Width-1)|%{$i+=(("$($a.GetPixel($_,$h)|select R,G,B)"|iex)['R','G','B']-ge192).count-eq3}}
[int]($i/($a.Height*$a.Width)*8)

Gets input $args[0] as the full image file-path, constructs a New Bitmap object into $a. This is just the internal object name; it supports JPG, PNG, etc.
We then double-loop through the .height and then the .width of the image, touching each pixel. We pull out the R,G,B values and then select those that are -greaterthanorequal to 192 and make sure that count is 3 (i.e., all of them are white-ish). That Boolean result is added into our accumulator $i.
We then divide out to get the percentage, multiply it by 8 to get the number of oktas, and then [int] to get just an integer output. (Note that this performs Banker's Rounding -- if that's not allowed it'll be several more bytes to change the rounding method.)

x86 Machine Code, 34 bytes
51
31 D2
AD
F7 D0
25 C0 C0 C0 00
75 01
42
E2 F3
C1 E2 03
DB 04 24
52
DB 04 24
DE F1
DB 1C 24
58
5A
C3

These bytes of code define a function that takes a bitmap input and returns an integer value indicating its oktas. As in C, arrays (like bitmaps) are represented as a pointer to the first element and a size/length. Thus, this function takes two parameters: the total number of pixels in the bitmap (rows × columns) and a pointer to the bitmap itself.
This code uses a custom register-based calling convention, where the bitmap pointer is passed in the ESI register and the bitmap size is passed in the ECX register. The result (oktas) is, per usual, returned in EAX.
As already stated above, the input is taken as a bitmap. Specifically, a 32-bpp format is used, in a little-endian format, but the alpha channel (highest-order byte) is ignored. This simplifies a lot of things, allowing us to simply iterate through each pixel and check its 32-bit RGB color value. A clever optimization is also used here. Instead of isolating each color component and checking whether it is >= 192, we just mask the entire 32-bit value by 0xC0C0C0 and test whether the result is >= 0xC0C0C0. This will evaluate to true for all "cloud" colors, and false for all "sky" (non-cloud) colors. Well, I thought it was clever! :-) It certainly saves a large number of bytes.
Therefore, in order to test this code, you will need to convert the input images to 32-bpp bitmaps. You cannot use Windows Paint for this, because it supports maximum of 24 bits-per-pixel. However, there are a number of other software solutions that can do it, such as Adobe Photoshop. I used this free tool, which converts a PNG to a 32-bpp BMP on Windows, meaning that you need only convert from JPEG to PNG (which Paint can do).
Other assumptions that I posit are eminently reasonable:

The bitmap is assumed to have a size greater than 0 (i.e., it is assumed to contain at least one pixel). This is reasonable because, when they sky is null, we have bigger problems than meteorology.
The direction flag (DF) is assumed to be clear so that we will iterate correctly through the bitmap using the LODSD instruction. This is the same assumption made by most x86 calling conventions, so it seems fair. If you don't like it, add 1 byte to the count for a CLD instruction.
The rounding mode for the x87 FPU is assumed to be set to round-to-nearest-even. This ensures that we get the correct behavior when we convert the number of oktas from a floating-point temporary to the final integer result, as verified by test case #4. This assumption is reasonable because this is the default state for the FPU and it is required to be maintained even in C code (where truncation is the default rounding behavior, forcing compilers that wish to be standards-compliant to generate inefficient code that changes the rounding mode, does the conversion, and then changes the rounding mode back).

Ungolfed assembly mnemonics:
; int ComputeOktas(void*    bmpBits  /* ESI */,
;                  uint32_t bmpSize  /* ECX */);
   push  ecx                  ; save size on stack
   xor   edx, edx             ; EDX = 0 (cloudy pixel counter)

CheckPixels:
   lodsd                      ; EAX = DS:[ESI]; ESI += 4
   not   eax
   and   eax, 0x00C0C0C0
   jnz   NotCloudy
   inc   edx
NotCloudy:
   loop  CheckPixels          ; ECX -= 1; loop if ECX > 0

   shl    edx, 3              ; counter *= 8
   fild   DWORD PTR [esp]     ; load original size from stack
   push   edx
   fild   DWORD PTR [esp]     ; load counter from stack
   fdivrp st(1), st(0)        ; ST(0) = counter*8 / size
   fistp  DWORD PTR [esp]     ; convert to integer, rounding to nearest even
   pop    eax                 ; load result
   pop    edx
   ret

Surely you haven't made it all this way down and are still wondering how the code works? :-)
Well, it's pretty simple. We just iterate through the bitmap one 32-bit value at a time, checking to see if that pixel RGB value is "cloudy" or "not cloudy". If it's cloudy, we increment our pre-zeroed counter. At the end, we compute: cloudy pixels⁄total pixels × 8
(which is equivalent to: cloudy pixels⁄total pixels ÷ 0.125).
I can't include a TIO link for this because of the need for input images. I can, however, provide you with the harness I used to test this on Windows:
#include <stdio.h>
#include <assert.h>
#include <Windows.h>

int main()
{
   // Load bitmap as a DIB section under Windows, ensuring device-neutrality
   // and providing us direct access to its bits.
   HBITMAP hBitmap = (HBITMAP)LoadImage(NULL,
                                        TEXT("C:\\...\\test1.bmp"),
                                        IMAGE_BITMAP,
                                        0, 0,
                                        LR_LOADFROMFILE  | LR_CREATEDIBSECTION);
   assert(hBitmap != NULL);

   // Get the bitmap's bits and attributes.
   DIBSECTION dib;
   GetObject(hBitmap, sizeof(dib), &dib);
   assert(dib.dsBm.bmBitsPixel == 32);
   uint32_t cx = dib.dsBm.bmWidth;
   uint32_t cy = abs(dib.dsBm.bmHeight);
   uint32_t sz = cx * cy;
   assert(sz > 0);

   int oktas = ComputeOktas(sz, dib.dsBm.bmBits);

   printf("%d\n", oktas);

   return 0;
}

Be careful with this, though! As defined above, ComputeOktas uses a custom calling convention, which a C compiler will not respect. You need to add code at the top of the assembly language procedure to load values from the stack into the expected registers, e.g.:
mov  ecx, DWORD PTR [bmpSize]
mov  esi, DWORD PTR [bmpBits]

C#, 313 bytes
namespace System.Drawing.Imaging{b=>{unsafe{int t=0,c=0,y=0,x,w=b.Width,h=b.Height;var d=b.LockBits(new Rectangle(0,0,w,h),(ImageLockMode)1,(PixelFormat)137224);for(;y<h;++y){var r=(byte*)d.Scan0+y*d.Stride;for(x=0;x<w*3;++t)if(r[x++]>191&r[x++]>191&r[x++]>191)c++;}b.UnlockBits(d);return(int)(c/(t+0d)/0.125);}}}

Obviously longer than my other answer but this one uses LockBits and unsafe code to directly access the image in memory; as such it is incredibly quick. I could probably remove the call to UnlockBits but it's more correct with it there.
Full/Formatted version:
namespace System.Drawing.Imaging
{
    class P
    {
        static void Main()
        {
            Func<Bitmap, int> f = b =>
            {
                unsafe
                {
                    int t = 0, c = 0, y = 0, x, w = b.Width, h = b.Height;

                    var d = b.LockBits(new Rectangle(0, 0, w, h), (ImageLockMode)1, (PixelFormat)137224);
                    for (; y < h; ++y)
                    {
                        var r = (byte*)d.Scan0 + y * d.Stride;

                        for (x = 0; x < w * 3; ++t)
                            if (r[x++] > 191 & r[x++] > 191 & r[x++] > 191)
                                c++;
                    }
                    b.UnlockBits(d);

                    return (int)(c / (t + 0d) / 0.125);
                }
            };

            string[] testCases =
            {
                @"Appearance_of_sky_for_weather_forecast,_Dhaka,_Bangladesh.JPG",
                @"spanish-sky.jpeg",
                @"why-is-sky-blue-1.jpg",
            };

            foreach (string testCase in testCases)
            {
                using (Bitmap bitmap = new Bitmap(testCase))
                {
                    Console.WriteLine(f(bitmap));
                }
            }

            Console.ReadLine();
        }
    }
}

JavaScript, 83 77 bytes
-6 bytes by ETHproductions
f=i=>(z=a=b=0,i.map(e=>{z=e<192||z;(++b%4)||((z||(a+=64))&&(z=0))}),a/b+1>>1)

Inputs
Picture #1
Picture #2
Picture #3
Picture #4
Demo

f=i=>(z=a=b=0,i.map(e=>{z=e<192||z;(++b%4)||((z||(a+=64))&&(z=0))}),a/b+1>>1)

window.onload = function(){
 var input = document.getElementById('input');
 input.addEventListener('change', handleFiles);
}
function handleFiles(e){
 var canvas = document.getElementById('canvas')
 var ctx = canvas.getContext('2d');
 var img = new Image;
 img.onload = function(){
  canvas.height = img.height
  canvas.width = img.width
  ctx.drawImage(img, 0,0);
  data = ctx.getImageData(0,0,canvas.width,canvas.height).data;
  console.log(f(data))//invoke f, send imageData as input
 }
 img.src = URL.createObjectURL(e.target.files[0]);
}
<input type="file" id="input"/><br>
<canvas id="canvas" style="max-width:400px"/>

Very nice solution. A handy trick with ES6 arrow functions is to wrap everything in parentheses, separated by commas (a=>(b,c,d)) instead of doing a=>{b;c;return d} or a=>eval("b;c;d"). This works unless you have a loop of some sort, in which case you'll probably be best off using the eval method.

C (POSIX), 103 bytes
Assumes input as BMP file on stdin.
b,c,i,m=0xc0c0c0;main(){lseek(0,54,0);for(;read(0,&b,3);c+=(b&m)==m,i++);printf("%d",(i+16*c)/(2*i));}

dc, 74 bytes
???*sa?[1+]ss[r1+r]st[?191<s]su0ddsd[0luxluxlux3=t1+dla>r]dsrxr8*la2/+la/p

Input is taken as a P3 ppm file, with all whitespace as newlines. Output is to STDOUT.
Try it online!

Mathematica 89 bytes
The following binarizes the picture and determines the fraction of clouds, i.e. white pixels.  Then it determines how many times .125 fits into the result.  It returns the floor of that value.
o@i_:=⌊8Tr@Flatten[ImageData@MorphologicalBinarize[i,.932],1]/Times@@ImageDimensions@i⌋

JavaScript (ES6), 218 bytes
(a,c=document.createElement`canvas`,w=c.width=a.width,h=c.height=a.height,x=c.getContext`2d`)=>x.drawImage(a,0,0)||x.getImageData(0,0,w,h).data.reduce((o,_,i,d)=>o+(i%4|d[i++]<192|d[i++]<192|d[i]<192?0:1),0)/w/h*8+.5|0

Takes an Image object as input, which can be created from an <image> element.
Test it out here on CodePen!
Alternative
If input can be taken as flat array of RGBA values, with dimensions: 82 bytes
(d,w,h)=>d.reduce((o,_,i)=>o+(i%4|d[i++]<192|d[i++]<192|d[i]<192?0:1),0)/w/h*8+.5|0

This input format is very similar to what this answer on meta suggests.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

authors: Евгений Новиков


text:
Risk Battle: Going Down
Given two lists of dice rolls for a battle in Risk, your program or function must output how many troops each player loses.
Background
 You do not have to read this, for it is merely background. Skip to "Task" subheading to continue unabated.
In the game of Risk, one player can attack another player (in fact, this is necessary to win). The outcome of a battle is determined by the roll of dice. Every battle occurs as a succession of sub-battles in which each player can lose up to 2 of their army pieces.
In a sub-battle, the defender and attacker each roll several dice whose number may vary based on circumstances irrelevant to this challenge. The highest-valued die of the attacker is compared to the highest-valued die of the defender. If the attacker's die is higher than the defender's die, the defender loses one piece. Otherwise, the attacker loses one piece.
Then, if both players have at least two dice, the second-highest valued dice of the two players are compared. Again, if the attacker's die is higher than the defender's die, the defender loses one piece. Otherwise, the attacker loses one piece.
(Defender wins ties. If both defender and attacker roll a 4, then the attacker loses a piece.)

 In this sub-battle from the Wikipedia article, the attacker's dice are red and the defender's dice are white. The highest of the attacker's dice is 4 and the highest of the defender's is 3. Since the attacker was higher, the defender loses a piece. The second-highest are 3 for the attacker and 2 for the defender. Since the attacker was again higher, the defender loses another piece. Thus in this sub-battle, the attacker loses no pieces and the defender loses 2 pieces.
Note that the third-highest pieces are not compared. This is because the defender has no more than two dice on a single sub-battle, so there are no third-highest pieces to compare ever.
Task
Given the unsorted dice rolls (integers in the range 1 to 6 inclusive) of both the attacker and the defender of a sub-battle of Risk in any convenient form, output the number of army pieces each player loses. The output may be in any convenient form, as long as it has different outputs to indicate the five possibilities. You must indicate what those different outputs are in your question.
The output is determined as follows: Start with def=0 and atk=0. If the greatest value of the list of dice rolls of the attacker is greater than the greatest value of the list of dice rolls of the defender, then increment def. Otherwise, increment atk.
If both lists of dice rolls have length at least 2, then: if the second-greatest value of the list of dice rolls of the attacker is greater than the second-greatest value of the list, then increment def and otherwise increment atk.
Finally, the program or function must output a unique identifier for each of the following 5 output possibilities:
  ╔═══╦═══╗
  ║atk║def║
  ╠═══╬═══╣
  ║ 1 ║ 0 ║
  ║ 0 ║ 1 ║
  ║ 2 ║ 0 ║
  ║ 1 ║ 1 ║
  ║ 0 ║ 2 ║
  ╚═══╩═══╝

Example
Defender: [3, 2]
Attacker: [2, 4, 1]
Max of defender is 3 and max of attacker is 4. 4>3, so def=1
Second of defender is 2 and second of attacker is 2. Not(2>2), so atk=1. The output could then be [1,1].
Test Cases
Defender
Attacker
Output (as [def,atk])
-----
[1]
[1]
[0,1]
-----
[6,6]
[1,1,1]
[0,2]
-----
[1,2]
[5,2,3]
[2,0]
-----
[5]
[3,4]
[0,1]
-----
[4]
[4,5]
[1,0]
-----
[1,3]
[1,2,3]
[1,1]
-----
[4]
[4,5,6]
[1,0]
-----
[4,5]
[6,2]
[1,1]
-----
[5]
[6,1,3]
[1,0]
-----
[5,5]
[4,4,1]
[0,2]
-----
[2,5]
[2,2]
[0,2]
-----
[6,6]
[4,4,3]
[0,2]
-----
[2,1]
[4,3]
[2,0]
-----
[4]
[1,5]
[1,0]
-----
[1]
[5,2]
[1,0]
-----
[6,2]
[4]
[0,1]
-----
[4,2]
[2,5,5]
[2,0]
-----
[2]
[6,6,2]
[1,0]
-----
[6]
[2,6]
[0,1]
-----
[3,1]
[1]
[0,1]
-----
[6,2]
[3,5,2]
[1,1]
-----
[4,2]
[1,1]
[0,2]
-----
[4,3]
[5,4,1]
[2,0]
-----
[5,6]
[1,2]
[0,2]
-----
[3,2]
[4,4]
[2,0]
-----
[2]
[6,3,4]
[1,0]
-----
[1,4]
[6,2,4]
[2,0]
-----
[4,2]
[2,5,4]
[2,0]
-----
[5]
[6,2,1]
[1,0]
-----
[3]
[2,5,4]
[1,0]
-----
[5,4]
[2]
[0,1]
-----
[6,3]
[2,6,5]
[1,1]
-----
[3,1]
[4]
[1,0]
-----
[4]
[6,6,5]
[1,0]
-----
[6,3]
[4,2]
[0,2]
-----
[1,6]
[5,4]
[1,1]
-----
[3,6]
[4,4]
[1,1]
-----
[5,4]
[5,1,1]
[0,2]
-----
[6,3]
[5,4]
[1,1]
-----
[2,6]
[1,2]
[0,2]
-----
[4,2]
[3,5,5]
[2,0]
-----
[1]
[1,2,1]
[1,0]
-----
[4,5]
[1,6]
[1,1]
-----
[1]
[3,5,1]
[1,0]
-----
[6,2]
[6,2]
[0,2]

Sample implementation
Python 2 or 3
def risk(atk_rolls,def_rolls):
    # set the rolls in descending order, e.g. [5,3,2]
    atk_rolls = sorted(atk_rolls,reverse = True)
    def_rolls = sorted(def_rolls,reverse = True)
    # minimum length.
    minlen = min(len(atk_rolls),len(def_rolls))
    atk_lost = 0
    def_lost = 0
    # compare the highest-valued rolls
    if atk_rolls[0]>def_rolls[0]:
        def_lost += 1
    else:
        atk_lost += 1
    if minlen == 2:
        # compare the second-highest-valued rolls
        if atk_rolls[1] > def_rolls[1]:
            def_lost += 1
        else:
            atk_lost += 1
    return [def_lost, atk_lost]

Specifications

The input may be taken as any form that clearly encodes only the defender's rolls and the attacker's rolls.
The output may be in any form that provides a unique output for each of the five possibilities listed above.
The defender's rolls are a list of 1 or 2 integers in the set [1,2,3,4,5,6]. The attacker's rolls are a list of 1 to 3 integers in the set [1,2,3,4,5,6].
Since this is code-golf, shortest code in each language wins! Do not let answers in golfing languages discourage you from posting answers in other languages.

Saw this on the sandbox, nice question

https://codegolf.meta.stackexchange.com/a/13456/61877

The attacker loses if its maximum roll is equal to the defender's highest roll, right?

Yes @Mr.Xcoder, the defender wins ties.

Hence I deleted the comment :)

NAND gates, 237

Created with Logisim
Inputs are 3-bit unsigned binary, entered on the left. Outputs (2 bits) are on the right.
It is too large to fit on the screen and Logisim can't zoom, so the image is black-and-white. Sorry :(
Works for all test cases.
There is likely a better way to do this using some memory circuit, allowing large sections to be reused.

Jelly,  12  11 bytes
NṢ€>/Ṡḟ-o-S

A monadic link taking a list of Defender, Attacker rolls (each as lists), returning an integer between -2 and 2 inclusive (defender losses - attacker losses):
result : [def, atk]
    -2 : [  0,   2]
    -1 : [  0,   1]
     0 : [  1,   1]
     1 : [  1,   0]
     2 : [  2,   0]

Try it online! or see a test suite (which maps the results to the OP format).
How?
NṢ€>/Ṡḟ-o-S - Link: list [list Def, list Atk]
N           - negate all the rolls
 Ṣ€         - sort €ach of the lists of -1*rolls (max rolls are to the left now)
    /       - reduce by:
   >        -   is greater than?  (when len(Atk) > len(Def) leaves trailing negatives)
     Ṡ      - sign (maps all negatives to -1; zeros and ones of comparison unchanged)
       -    - literal -1
      ḟ     - filter discard (remove the -1s)
         -  - literal -1
        o   - logical or, vectorises (replaces the zeros with minus ones)
          S - sum

Husk, 10 bytes
M#eI¬¤z>Ö>

Try it online!
Input as two separate lists of rolls, output as in the op.
Explanation
¤z>Ö> sorts each list in descending order and then zips them comparing corresponding elements (and truncating the longer list).
M#eI¬ creates a 2-element list (e) with counts (#) of truthy values (through identity I) and falsy values (through logical negation ¬)

JavaScript (SpiderMonkey), 97 83 78 bytes
d=>a=>{for(u=v=0;d.sort()>[]&a.sort()>[];)a.pop()>d.pop()?u++:v++
return[u,v]}

Try it online!
-4 bytes and fixed thanks to @ovs and @Craig Ayre
-1 byte thanks to @Shaggy

Doesn't work for one attacker against two defenders.

Oh hmm I didn't think about that. I'll fix it

This might work.

@ovs's solution passes all test cases, you can save a few bytes too (tio link was too large): d=>a=>{for(u=v=0;d.sort()>[]&a.sort()>[];)a.pop()>d.pop()?u++:v++;return[u,v]}

The first line break is unnecessary and costing you a byte.

Ah yes, you're right

Retina, 82 bytes
%O^`.
((.)+).*(¶(?<-2>.)+)(?(2)(?!)).*
$1$3
O$`.
$.%`
\d
$*1D
(1+)D1*\1

1+D
A
O`.

Try it online! First line of input is attacker's dice, second is defender's dice. Returns (on separate lines) AA, AD, DD, A or D as appropriate.

Python 2, 83 75 bytes
x=0
k=map(sorted,input())
while all(k):x+=cmp(*map(list.pop,k))or 1
print-x

Try it online!
Output is defender losses - attacker losses

MATL, 23 bytes
oH2$S1&Y)Y&t1M>t~b,Y&sD

Try it online!
Not sure why defenders are allowed more dice than attackers, but maybe I am not that well versed in Risk. The core program is just >t~,sD, all the other bytes are there to allow for different input lengths, with a bit of sorting thrown in. Input is attacker followed by defender, output is attacker losses followed by defender losses.
o    % Convert input to numeric array, padding with zeroes
H2$S % Sort row-wise (specified to prevent 1v1 sorting)
1&Y) % Split attacker/defender
Y&t  % Logical and to filter out excess dice. Duplicate for 'do twice' later.
1M>  % Get throws again, decide who won
t~   % And the inverse to decide who lost
b,   % Bubble filter to the top. Do twice:
  Y& % Apply filter
  sD % Sum of losses. Display.

Perl 5, 66 + 1 (-a) = 67 bytes
@A=sort split/ /,<>;$b+=@A?pop@A>$_?-1:1:0for reverse sort@F;say$b

Try it online!
Input:
Two lines.  First line is defender (player 1), second is attacker (player 2).  Individual rolls separated by spaces.
Output:
Indicates effective change in defender's strength vs. attacker.
Output Attacker Defender
   2      0        2        Defender wins both
   1      0        1        Defender wins the only roll
   0      1        1        Attacker wins first, defender wins second
  -1      1        0        Attacker wins the only roll
  -2      2        0        Attacker wins both rolls

"The program or function must output a unique identifier for each of the 5 output possibilities." Yours has two outputs for [1,1]. Please edit your answer to fix this ( just sort or sum)

What's wrong with six?  It's more specific.  :)
I changed it at a cost of 6 bytes.

R, 46 bytes
function(x,y)s(s(y,T)[1:2]>s(x,T)[1:2])
s=sort

Try it online!
All this does is three sorts and one comparison... plus extracting the first two elements in the middle.
Input is two vectors of dice rolls.
Output encoded as follows:
╔═══╦═══╗
║atk║def║
╠═══╬═══╣
║ 1 ║ 0 ║ TRUE
║ 0 ║ 1 ║ FALSE
║ 2 ║ 0 ║ TRUE  TRUE
║ 1 ║ 1 ║ FALSE TRUE
║ 0 ║ 2 ║ FALSE FALSE
╚═══╩═══╝

Works because extraction in R does not recycle its argument, but pads the result with NA to get to the requested length.

Jelly, 30 bytes
0,0‘⁸Ṁ€</¤¦‘⁸ḟ"Ṁ€⁺</¤¦⁸L€Ṃ>1¤¡

Try it online!
Veeeeeeeery ungolfed! >_<
Outputs values exactly as in test cases.

Wow, this seems way too long even to me :P


text:
Within Fibonacci Numbers
The Challenge
Given an integer input, return the first Fibonacci number that contains the input within itself along with the index of that Fibonacci number (indexes starting at 0 or 1 - up to you, but please mention which in your answer). For example, if given the input of 12, the program would return 26: 121393 as 12 is found within the number (121393) and it is at index 26 of the Fibonacci numbers.
Examples
Given the input:
45

Your program should output:
33: 3524578

Input:
72

Output:
54: 86267571272

Input:
0

Output:
0: 0

Input:
144

Output:
12: 144

Scoring
This is code-golf, so the shortest answer in each language wins.

Can we choose to have 1-indexing instead?

@Mr.Xcoder Sure, I updated the challenge. :)

Not a duplicate, but pretty close to this challenge.

The 12th fibonacci number is 144, so the last test case should be 12: 144.

Thread over on math regarding whether Fibonacci sequence is normal or not (this question presumes it is).

@fireflame241 Good catch! I have fixed the example. :)

Do we have to use a colon as a separator? Can we output an array/list?

@AdmBorkBork I think this question even goes a bit further in its presumtion than that thread. That thread would imply that every natural number would appear at some point in the constant, but this would allow overlapping between two numbers: 32 would be in 8,1[3,2]1 already instead of in 832040.

Related question on math.SE about whether this has a solution for any x

@JarkoDubbeldam Good distinction. Thanks for the clarification.

@Shaggy the colon is not mandatory, it's just a suggestion.

Jelly, 10 bytes
0ÆḞ©w¥1#;®

Try it online!
How it works
0ÆḞ©w¥1#;®  Main link. Argument: n

0           Set the return value to 0.
       #    Call the second link to the left with arguments k = 0, 1, 2, ... until
      1     one match has been found.
     ¥        Combine the two links to the left into a dyadich chain.
 ÆḞ             Compute the k-th Fibonacci number...
   ©              and copy it to the register.
    w           Yield 1 if n occurs inside the Fibonacci number, 0 otherwise.
         ®  Yield the value stored in the register.
        ;   Concatenate the index and the Fibonacci number.

You used the same trick as mine. :)

@EriktheOutgolfer As yours?

Didn't post it, but generally I didn't use D either...

Python 2, 56 bytes
f=lambda n,i=0,a=0,b=1:`n`in`a`and(i,a)or f(n,i+1,b,a+b)

Try it online!

Perl 6, 30 bytes
{first :kv,/$_/,(0,1,*+*...*)}

Try it online!
first is a function that returns the first element of a sequence that passes a test, and it conveniently takes a :kv adverb that tells it to return both the key (index) and the matching value.

Assuming you can return a Pair object, you can use the :p adverb instead of :kv.

Batch, 104 bytes
@set/an=x=0,y=1
:l
@call set t=%%x:%1=%%
@if "%t%"=="%x%" set/an+=1,x+=y,y=x-y&goto l
@echo %n%: %x%

Works for n=0..45 due to the limited range of Batch's integer arithmetic. Explanation: Batch doesn't have a built-in match test, but it does have an operator that can replace literal strings with other literal strings, so for example if "%s:l=%"=="%s%" is true if %s% is not empty but does not contain l. The use of call is then a trick to substitute %1 (the input) into the replacement operator, however call doesn't work on control flow statements so an intermediate temporary assignment is necessary.

Jelly, 15 bytes
³DẇÆḞ¬
0‘Ç¿µ,ÆḞ

Try it online!

43 seconds too late

Javascript ES6, 68 chars
n=>eval('for(q=x=0,y=1;!`${x}`.match(n);++q)[x,y]=[y,x+y];q+": "+x')

Test:

f=n=>eval('for(q=x=0,y=1;!`${x}`.match(n);++q)[x,y]=[y,x+y];q+": "+x')
console.log([45,72,0,144].map(f).join`
`)

Python 3, 76 bytes
f=lambda n,l=[1,0]:str(n)in str(l[1])and(len(l)-2,l[1])or f(n,[l[0]+l[1]]+l)

Emojicode, 133 bytes
a 0b 1i 0☁a 1010b➕a ba➖b ai➕1ii 10a 10

Try it online!

R, 65 bytes
f=function(x,n=1,a=1,b=0)`if`(grepl(x,b),c(b,n-1),f(x,n+1,a+b,a))

Standard recursion to generate Fibnums, but instead of terminating based on n, terminates when b matches the regex x. This actually works surprisingly well. I assumed that using regex with numerics would require a lot of hassle converting them to strings, but that doesn't seem to be necessary :)
This also has to overshoot the recursion by 1 step, by checking on b instead of a and then substracting 1 from n. This is to make sure f(0) works properly.
This fails for most values when input exceeds 1001, because of maxint. If we replace a and b for bigints, this works for higher inputs (current testing is at x = 11451)
f=function(x,n=1,a=gmp::as.bigz(1),b=gmp::as.bigz(0))`if`(grepl(x,b),c(b,n-1),f(x,n+1,a+b,a))

C# (.NET Core), 99 bytes
n=>{int a=0,b=1,c,d=0;for(;b.ToString().IndexOf(n.ToString())<0;c=a,a=b,b+=c,d++);return d+": "+b;}

Try it online!
Takes input as an integer, returns a string with the output.

Haskell, 84 bytes
import Data.List
f=0:scanl(+)1f
g n=filter(isInfixOf(show n).show.snd)(zip[0..]f)!!0

Try it online!

Japt, 17 14 bytes
Saved 3 bytes thanks to @JustinMariner
_Å¬øU}a@[XMgX]

Try it online!
Explanation
_Å¬øU}a@[XMgX]      Implicit: U = input integer
      a@            For each integer X in [0, 1, 2, ...]:
        [XMgX]        take [X, Fibonacci(X)].
_    }a             Return the first pair where
 Å                    all but the first item
  ¬                   joined on the empty string (simply returns Fibonacci(X) as a string)
   øU                 contains U.
                    Implicit: output result of last expression

14 bytes: _Å¬øU}a@[XMgX]. Using s1 q  to get last item, which allows dropping the <space>s

@JustinMariner That's... that's genius :-)

Dyalog APL, 39 bytes
{⍺←0⋄∨/(⍕⍵)⍷⍕x←1∧+∘÷/0,⍺/1:⍺,x⋄(1+⍺)∇⍵}

Using tail recursion. Don't attempt 72, it'll break your machine because its recalculating fibonacci all over every call.
Try it online!

JavaScript ES6, 79 78 75 bytes
-1 byte by Step Hen
-3 bytes by Neil
i=>eval('d=a=b=1;while(!~(a+"").indexOf(i)){c=b;b=a+b;a=c;d++};d+": "+a')

You can use eval() instead of { return} to save a byte, and you can drop the t= since you aren't using recursion: i=>eval('d=a=b=1;while(!~(a+"").indexOf(i+""){c=b;b=a+b;a=c;d++};d+": "+a')

String.prototype.indexOf automatically converts its parameter to a string, no need to do it explicitly. Also you appear to have copied @StepHen's typo (you have more (s than )s).

@Neil woops my bad

Mathematica, 119 bytes
1-indexed
(T=ToString;If[(h=#)==0,"0:0",a=#&@@Select[k=T/@(Array[Fibonacci,9#]),StringContainsQ[#,T@h]&];Min@Position[k,a]":"a])&

Try it online!

Actually, 13 bytes
╗1⌠F$╜@c⌡╓i;F

Try it online!
Explanation:
╗1⌠F$╜@c⌡╓i;F
╗              save input in register 0
 1⌠F$╜@c⌡╓     smallest non-negative integer n where the following function returns truthy:
   F$            nth Fibonacci number, stringified
     ╜@c         count occurrences of input
          i;F  flatten the list, duplicate the index, and push the Fibonacci number at that index

PHP, 80 bytes
<?php for($a=1,$b=$n=0;strpos($a=-$a+$b=$a+$b,"$argv[1]")<-1;$n++);echo"$n: $a";

The script is quite straightforward, simply storing the current and next terms of the sequence in $a and $b throughout. To allow for the 0th term of 0, $a and $b are initially assigned the values for the -1th term (1) and 0th term (0) respectively.
Both values are recalculated in a single expression, which is two assignments in one; effectively:
$b = $a + $b; // The next term is the sum of the two previous terms
$a = $b - $a; // The current term is now recalculated from the next and the previous

If the input value matches the beginning of the term, the strpos() function will return 0 (which is falsey and would give a false negative), but in the Wonderphul World of PHP, although false == 0 is true and false < 0 is false, false < -1 is true! And so, using this comparison saves five bytes compared to !==false.

PHP, 163 141 bytes
<?php $x=fgets(STDIN);$b=[0,1];if($x<1)$b=[0];for(;($c=count($b)-1)&&strpos($b[$c],$x)===false;){$b[]=$b[$c]+$b[$c-1];}die($c.': '.$b[$c]);?>

Try it online!
Uses $b[0] = 0; and $b[1] = 1; for the start of fib sequence

Perl 5, 67 + 1 (-p) = 68 bytes
@f=(0,1);push@f,$f[-1]+$f[-2]while($f[-2]!~/$_/);$_=--$#f." $f[-1]"

Try it online!

PHP, 93 bytes
for($a[0]=$a[1]++;!strpos(" $a[$i]","$argv[1]");$a[$i+2]=$a[$i+1]+$a[$i++]);echo"$i: $a[$i]";

Simple loop through the Fibonacci sequence. The check for our input number is done in strpos(" $a[$i]","$argv[1]"); the extra space is because strpos will return false-y if the 'needle' is found at the beginning of the string. We end if the input is found and echo out the required string.
Try it online!

Common Lisp, 105 bytes
(lambda(x)(do((a 0 b)(b 1(+ a b))(i 0(1+ i)))((search(#1=format()"~a"x)(#1#()"~a"a))(#1#()"~a: ~a"i a))))

Try it online!