[Question]
  [
You should have heard about the **[Fibonacci Numbers](https://en.wikipedia.org/wiki/Fibonacci_number)**, often called the Fibonacci Sequence. In this sequence the first two terms are 0 and 1, and every number after the first two is the sum of the two preceding ones. In other words, `F(n) = F(n-1) + F(n-2)`.
Here are the first 20 Fibonacci numbers:
```
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
```
---
## Task:
Given an integer `x`, compute the arithmetic mean (the average) of the prime Fibonacci Numbers up to the `x` number of the Fibonacci Sequence.
## Rules:
* the Fibonacci sequence starts with 0 and 1 for this challenge
* `3 < x < 40`, because higher values of `x` might cause some huge execution time or overflows and smaller values have no output
* 1 is ***NOT*** prime, since it only has 1 divisor
* the arithmetic mean should include decimals, if it's the case, or should be displayed as an exact fraction
* you are only allowed to take `x` as input and the code needed to take the input does not count (e.g: if you need something like `x = input()`, you should not take it into consideration when counting the bytes)
---
## Examples:
**Ex. 1:** For `x=10`, the output is `5.75`, because the 10th Fibonacci number is `55` and the prime Fibonacci numbers up to `55` are `2, 3, 5, 13`, their average being `5.75`
Following the explanation from example 1, other examples are:
**Ex. 2:** For `x=15`, the output is `57.5`
**Ex. 3:** For `x=20`, the output is `277.428571428571`, or any other close approximation. In this case `277.4286`, for instance, is an accepted value
**Ex. 4:** For `x=11`, the output is `22.4`
**Ex. 5:** For `x=30`, the output is `60536.4444444444`, or any other close approximation, such as `60536.444`
---
## Leaderboard:
```
var QUESTION_ID=112025,OVERRIDE_USER=59487;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
---
To change the leader, submit a shorter valid solution. Your code should be as short as possible, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Good luck!
  
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
s=2.;a=b=c=1
exec"p=2**a%a==2;c+=p;s+=a*p;a,b=b,a+b;"*input()
print s/c
```
[Try it online!](https://tio.run/nexus/python2#BcFBCoAgEAXQvacIIahRiqTd8A8zDi7cyJAG3d7emx3pYEGG4nLlK@oNiUhWARJrgHEPEDKWmJGjhMyearN3bLuzp7ax9FPnvH8 "Python 2 – TIO Nexus")
Python doesn't have useful arithmetic built-ins for this, so we do things by hand. The code iterates through Fibonacci numbers via `a,b=b,a+b` starting from `a=b=1`. 
The [Fermat primality test](https://en.wikipedia.org/wiki/Fermat_primality_test) with base 2 is used to identify primes as `a` where `2^a == 2 (mod a)`. Though this only checks for probable primes, none of the [false positives](https://oeis.org/A001567) are within the first 40 Fibonacci numbers.
The current sum `s` and count `c` of primes are updated each time a prime is encountered, and their ratio (the mean) is printed at the end. Because the prime check misses `a=2` and it's guaranteed to be in the input range, the sum starts at 2 and the count starts at 1 to compensate.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ÆḞ€ÆPÐfµS÷L
```
[Try it online!](https://tio.run/nexus/jelly#@3@47eGOeY@a1hxuCzg8Ie3Q1uDD233@H24HikT@/29ooKNgaKqjYASiDXUUjA0A "Jelly – TIO Nexus")
### How it works
```
ÆḞ€ÆPÐfµS÷L  Main link. Argument: n (integer)
ÆḞ€          Map the Fibonacci atom over [1, ..., n].
   ÆPÐf      Filter by primality.
       µ     Begin a new chain. Argument: A (array of Fibonacci primes)
        S    Yield the sum of A.
          L  Yield the length of A.
         ÷   Compute the quotient.
```
[Answer]
# Mathematica, 38 bytes
```
Mean@Select[Fibonacci@Range@#,PrimeQ]&
(* or *)
Mean@Select[Fibonacci~Array~#,PrimeQ]&
```
**Explanation**
```
Mean@Select[Fibonacci@Range@#,PrimeQ]&  
                                     &  (* For input # *)
                      Range@#           (* List {1, 2, 3, ... #} *)
            Fibonacci@                  (* Find the corresponding fibonacci numbers *)
     Select[                 ,PrimeQ]   (* Select the prime terms *)
Mean@                                   (* Take the Mean *)
```
[Answer]
# [Perl 6](https://perl6.org), 51 bytes
```
{sum($/=[grep *.is-prime,(0,1,*+*...*)[0..$_]])/$/}
```
[Try it](https://tio.run/nexus/perl6#NY7LboMwEEX3/opRhBoDZniERyUKn9BVdyGqKuJWliBYNm5TIb6su/4YdR1ld2buGc01msNniX1NjKUXrueajN/w0E9nDs22aDNSL26OH4pLCFDoSCoxckYTlrIgDBAx8I8Jovd6OvmxF6/b@6QIwCAuXFO/s/j7g1oOYqYxPOGXbmEftfsbxnfh2YxciZ5ELVDoxEWamUHHr5L3Mz@DD4v1bLFOcW2GGRr4b0hDZ/q1DW21NynVdIXw5jAI7/cMdoszV2haWG75uiPrliZgXxZYFSQtHFZYkMxts6rCPHssSZq6McOcHFxSJsWhxDzP/wA "Perl 6 – TIO Nexus")
## Expanded:
```
{
  sum(
    $/ = [                # store as an Array in $/
      grep
        *.is-prime,       # find the primes
        (
          0, 1, *+* ... * # Fibonacci sequence
        )[ 0 .. $_ ]      # grab the indicated values in the sequence
    ]
  )
  /
  $/   # use the Array as a number (elems)
}
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 10 bytes
Code:
```
R♂F;Mr♂P∩æ
```
Explanation:
```
R            # On the input, create the range [1 .. input].
 ♂F          # Map the nth Fibonacci command over it.
   ;M        # Duplicate and get the maximum of the list.
     r       # Create the range [0 .. maximum - 1].
      ♂P     # Map the nth prime operator over each element (zero-indexed).
        ∩    # Intersection of both.
         æ   # Get the mean and implicitly display.
```
Uses the **CP-437** encoding. [Try it online!](https://tio.run/nexus/actually#@x/0aGaTm7VvEZAKeNSx8vCy//8NTQE "Actually – TIO Nexus")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
lOi:"yy+]vtZp)Ym
```
[Try it online!](https://tio.run/nexus/matl#@5/jn2mlVFmpHVtWElWgGZn7/7@hAQA "MATL – TIO Nexus")
### Explanation
```
lO     % Push 1, then 0. This way the generated numbers with indices 1, 2, 3, ...
       % will be 1, 1, 2, ... as required
i      % Input n
:"     % Do the following n times
  yy   %   Duplicate top two numbers
  +    %   Add
]      % End
v      % Concatenate all numbers into a column vector
t      % Duplicate
Zp     % Vector of logical values: true for prime numbers, false otherwise
)      % Apply that vector as an index. This keeps only prime numbers
Ym     % Mean. Implicitly display
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~75~~ 71 bytes
```
@(n)mean((t=fix(((1+(s=5^.5)).^(x=1:n)-(1-s).^x)/s./2.^x))(isprime(t)))
```
Anonymous function that uses [Binet's formula](https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression). Input and output are in the form of function arguments.
[Try it online!](https://tio.run/nexus/octave#dY3BDoIwEETvfMVeTHajAsVw0ZD4JSYb2EKTthi2Kn49gvHqXN7MYWaWK0YKwhExNdbNiGj2qE19y2ui/IZzY86RjmiOusaZCs2LajOETu@TC4KJiBYLDXDUC/zXDnr3FEiDgH3ENrkxAkPkIJkdp8AJ/Bj7/@1uPfT8hif7hyi8XBqAvYdOWhfYa2bRlHSAFfUX1S@ZL04lbStJNEHLKrp8AA)
[Answer]
# Maxima, 49 bytes
```
f(n):=mean(sublist(makelist(fib(x),x,n),primep));
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~269~~ ~~264~~ ~~254~~ 218 bytes
* Thanks to *Fatalize* for saving 37 bytes!
* Thanks to *Emigna* for saving 9 bytes!
I'm fairly certain that I could golf some more bytes down.
```
X/X:-X<3.
N/R:-A is N-1,B is N-2,A/C,B/D,R is C+D.
2^0^0.
C^S^E:-G is C-1,G/M,G^Q^R,(p(M)->S=M+Q,E is R+1;S=Q,E is R).
a(X,S):-X^R^Q,S is R/Q.
p(N):-N*(N-1).
p(2).
p(3).
N*2:-N mod 2=\=0.
N*C:-N mod C=\=0,D is C-1,N*D.
```
Run it as **`a(15, R).`** for **x = 15**, **R** is the output variable.
[Try it online!](https://tio.run/nexus/prolog-swi#NY4xC8MgFIR3f4WjJk9NDF3SWkg0ZIqgLg5FCHTpUBro/yfVlCzHu@943O1RxJ7FW8eRFb5nA359sWUtjP9DwiA0jMKAL0DXhiOZmtRwpFNIU8/mg@ePWSwwJ5c8kI0slN2DWmoHU8l93V6DOg3laCURAs3NyScH4cDCcbQRm6mtSN5Ai5WHdlltJXOC358nluqhmkL0SXQhYM4ttjJ831fSXqDU/QA "Prolog (SWI) – TIO Nexus")
---
A more readable version:
```
fibonacci(1, 1) :- !.
fibonacci(2, 2) :- !.
fibonacci(N, R) :-
  N0 is N - 1,
  N1 is N - 2,
  fibonacci(N0, R1),
  fibonacci(N1, R2),
  R is R1 + R2.
listed(2, 0, 0) :- !.
listed(C, S, Successes) :-
  C0 is C - 1,
  fibonacci(C0, Result),
  listed(C0, S0, S1),
  (
    is_prime(Result)
    ->
      S = Result + S0, Successes is S1 + 1
    ; S = S0, Successes is S1
  ).
f(X, S) :-
  listed(X, R, Q),
  S is R / Q.
is_prime(Num) :- is_prime(Num, Num - 1).
is_prime(2).
is_prime(3).
is_prime(Num, 2) :- Num mod 2 =\= 0, !.
is_prime(Num, C) :-
  Num mod C =\= 0,
  C0 is C - 1,
  is_prime(Num, C0).
```
[Answer]
# [Röda](http://github.com/fergusq/roda), ~~98~~ ~~94~~ 93 bytes
```
f n{z=0;i=1;j=1;s=0;seq 2,n-1|{|_|c=i+j;i=j;j=c;seq 2,c-1|{z+=1;s+=c}if[c%p>0]()for p}_[s/z]}
```
It's a function that returns the result as a floating point number.
Ungolfed version:
```
function f(n) {
    i = 1
    j = 1
    sum = 0
    num = 0
    seq(2, n-1) | for _ do
        /* calculate next fibonacci number: */
        c = i+j
        i = j
        j = c
        /* if it's prime: */
        {
            num += 1
            sum += c
        /* primality test: */
        } if [c%p > 0]() for p in [seq(2, c-1)]
    done
    return sum/num
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
!ÅF¹£DpÏDOsg/
```
[Try it online!](https://tio.run/nexus/05ab1e#@694uNXt0M5Di10KDve7@Ben6///b2QAAA)
or as a [Test suite](https://tio.run/nexus/05ab1e#MzRQMDRVMAKShgrGBppllf8VD7e6VR5a7FJwuN/Fvzhd/3@l0uH9VgqH9yvp/AcA)
**Explanation**
```
!ÅF             # get a list of fibonacci numbers up to fac(input)
   ¹£           # take the first input elements of that list
     D          # duplicate
      p         # isprime on the copy
       Ï        # keep the fibonacci numbers which are true in the isprime list
        D       # duplicate the list of fibonacci primes
         O      # sum the list
          s     # swap the other copy to the top of the stack
           g    # get its length
            /   # divide sum by length
```
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 11 bytes
```
S.b#_P)'sl/
```
[Try it online!](https://tio.run/nexus/pyke#@x@sl6QcH6CpXpyj//@/oQEA "Pyke – TIO Nexus")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 129 bytes
```
?sa0sb1sd0ss0sz[[lF1+sF]sqlelG!=q]si[ls+sslz1+sz]sw[lddlb+dsdrsbdsG2se0sF[lGdle%0=ile1+dse<p]dspxlF0=wla1-dsa1<c]dscxEkls1-lz1-/p
```
A Fibonacci number generator and primality checker all in one. Nice.
[Try it online!](https://tio.run/nexus/dc#DcyxDoIwFIXhZ3FwIo33OkOcLA/RdCi9TSSeKHgGSN@bGbv@X/KfDybhpDQhhTUEeO3oI1cUjJdhjZwD2JGoDWrkFmCGqTPaj5NxvLMIfcBoKFcZZhRtWPolGpcdXoYNSZ0xaZ9by/vzDaprQ3dbzlPl@HxdTvlV/g "dc – TIO Nexus")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
Afṗ↑İf
```
[Try it online!](https://tio.run/##yygtzv6fm18enPqoqfG/Y9rDndMftU08siHt////0YYGOoamOkZA0lDH2CAWAA "Husk – Try It Online") Outputs the mean as an exact rational number.
### Explanation
```
Afṗ↑İf  (Let X denote the argument.)
A       Take the arithmetic mean of
   ↑      the first X values of
    İf     the infinite list of Fibonacci numbers,
 fṗ      filtered for primality.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~14~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ò!gM fj Ë/Fl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=8iFnTSBmaiDLL0Zs&input=MzA)
[Answer]
# perl, 91 bytes
```
$b=1;map{($a,$b)=($b,$a+$b),$p=("x"x$b)!~/^(.|(..+)\2+)$/,$s+=$b*$p,$c+=$p}2..$x;print$s/$c
```
Cuold have been 8 bytes shorter if the modulo pseudoprime test worked as well in perl as in the python answer:
```
$b=1;$s=2;map{($a,$b)=($b,$a+$b),$p=2**$b%$b==2,$s+=$b*$p,$c+=$p}2..$x;print$s/++$c
```
...but this gives wrong answer for input > 16 in perl.
[Answer]
# Axiom, 104 bytes
```
g(n)==(y:=x:=r:=0;repeat(x>n=>break;j:=fibonacci(x);x:=x+1;if prime?(j)then(r:=r+j;y:=y+1));y=0=>-1;r/y)
```
ungolfed, test code and results
```
f(n)==
  y:=x:=r:=0
  repeat
     x>n=>break
     j:=fibonacci(x)
     x:=x+1
     if prime?(j) then(r:=r+j;y:=y+1)
  y=0=>-1
  r/y
(3) -> [[i,g(i)::Float] for i in [1,2,3,10,15,20,11,30,50]]
   Compiling function g with type PositiveInteger -> Fraction Integer
   (3)
   [[1.0,- 1.0], [2.0,- 1.0], [3.0,2.0], [10.0,5.75], [15.0,57.5],
    [20.0,277.4285714285 7142857], [11.0,22.4], [30.0,60536.4444444444 44444],
    [50.0,309568576.1818181818 2]]
```
i try to duplicate the matematica, octave etc languages entry, if one not count the mean() function, to implement it would be here **62 bytes** so good too
```
mean(a:List Float):Any== 
    i:=1; s:=0.0
    repeat  
       if~index?(i,a)then break
       s:=s+a.i
       i:=i+1
    i=1=>[]
    s/(i-1)
--62 bytes
f(x:NNI):Any==mean(select(prime?,[fibonacci(i)for i in 1..x]))
```
[Answer]
# JavaScript ES6, ~~137~~ ~~136~~ ~~118~~ 113 bytes
```
m=
n=>(a=[],(f=x=>a[x]=x<2?x:f(--x)+f(--x))(n),eval((a=a.filter(x=>eval("for(y=x;x%--y;);y==1"))).join`+`)/a.length)
console.log(m(10))
console.log(m(15))
console.log(m(20))
console.log(m(11))
console.log(m(30))
```
---
## History
### 118 bytes
```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>eval("for(y=x;x%--y;);y==1"))).join`+`)/a.length)
```
### 136 bytes
```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>x>1&&!Array(x).fill().some((i,j)=>j>1&&!(x%j)))).join`+`)/a.length)
```
### 137 bytes
```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>{d=x;while(--d>1)if(!(x%d))return 0;return x>1})).join`+`)/a.length)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ÆḞ€ẒƇÆm
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//w4bhuJ7igqzhupLGh8OGbf///zEw "Jelly – Try It Online")
The newest version of Jelly really helps with this. This is essentially identical to [Dennis' answer](https://codegolf.stackexchange.com/a/112026/66833) but uses the newer features, so go upvote his answer.
## How it works
```
ÆḞ€ẒƇÆm - Main link. Takes n on the left
ÆḞ€     - i'th Fibonacci number for each i in [1, 2, .., n]
    Ƈ   - Comb; Keep those for which the following is true:
   Ẓ    -   Is prime?
     Æm - Take the arithmetic mean
```
[Answer]
# [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 71 bytes
```
> Input
> fₙ
>> 2ᶠ1
>> L’
>> Select∧ 4 3
>> mean(5)
>> Output 6
```
Unfortunately, no TIO as this relies on v3 features, and v3 isn't on TIO. However, you can tell it by downloading and running the interpreter in the linked GitHub repo
## How it works
```
> Input
Here, we "define" line 1 to hold our input integer, n
> fₙ
On line 2, we store an infinite list of Fibonacci numbers
>> 2ᶠ1
We then use the ᶠ dyad to take the ᶠirst n elements from the infinite list
>> L’
This line is a "functional operator line". It is passed a value on the Left and returns the ’ (prime) operator result on that value
>> Select∧ 4 3
We now take the list of Fibonacci numbers and Select those which return true when run through line 4
>> mean(5)
>> Output 6
Finally, we take the mean of the resulting list, before outputting it
```
]