longrun_function(n,k,pb) { # n:length of the whole binary sequence (independent) (n>2) # # pb : probibility of sucess for each trial# # k:length of the longest run L# # outcome : P(L>=k)# a_matrix(1,k,1) b_diag(a,k) c_matrix(0,1,k) p0_cbind(1,c) U_rbind(a,0) c_cbind(c,1) M_cbind((1-pb)*a, pb*b) M_rbind(M,c) Mn_M%*%M for (i in 3:n) { Mn_Mn%*%M } 1-p0%*%Mn%*%U } Elongrun_function(n,pb) { # outcome : expectation of L # s_0 for (k in 1:n) { s_s+longrun(n,k,pb) } s }