#Dev Patel- 2434793

#Fibonacci and Pell Numbers
n <- 0:199            # I am creating index from 0 to 199
N <- length(n)         # here I am finding total count = 200

# I am making empty boxes for data so I can store numbers later
fib   <- numeric(N)
pell  <- numeric(N)
q     <- numeric(N)        # this is for pell lucas sequence
approx <- rep(NA_real_, N) # this is for sqrt2 guess
diff5  <- rep(NA_real_, N) # this is for 5 decimal diff
acc    <- rep(NA_integer_, N) # this is for accuracy count

# I am setting first two numbers
fib[1]  = 0; fib[2]  = 1
pell[1] = 0; pell[2] = 1
q[1]    = 2; q[2]    = 2

# now I am making all next numbers
for (i in 3:N) {
  fib[i]  = fib[i-1] + fib[i-2]        # this is fib rule
  pell[i] = 2*pell[i-1] + pell[i-2]    # this is pell rule
  q[i]    = 2*q[i-1] + q[i-2]          # this rule is for pell lucas
}

# checking first few numbers just to be sure it's working
head(fib)
head(pell)
head(q)

#Approximation of sqrt2

# now I am finding actual value of sqrt2
root2_val <- sqrt(2)
root2_str <- formatC(root2_val, format="f", digits=20) #saving it as string for comparison

# now I am finding value of approx, diff, and acc
for (i in 1:N) {
  if (pell[i] > 0) {
    #finding approximation for question 2
    approx[i] <- q[i] / (2 * pell[i])             # guess for sqrt2 using pell and pell lucas
    
    #difference up to 5 decimal places for question 3
    diff5[i]  <- round(abs(approx[i]-root2_val),5)# checking how close it is to real sqrt2
    
    # matching decimals for accuracy for question 4
    # I am changing both numbers to text to compare each digit after decimal
    a_str <- formatC(approx[i], format="f", digits=20)
    a_dec <- strsplit(a_str,"\\.")[[1]][2]
    r_dec <- strsplit(root2_str,"\\.")[[1]][2]
    
    # I am counting how many digits are same after dot
    count <- 0
    maxk <- min(nchar(a_dec), nchar(r_dec))
    for (k in 1:maxk) {
      if (substr(a_dec,k,k)==substr(r_dec,k,k)) {
        count <- count + 1
      } else {
        break
      }
    }
    acc[i] <- count # saving that count for this row
  } else {
    
    # if pell value is 0 then I am keeping NA
    approx[i] <- NA_real_
    diff5[i]  <- NA_real_
    acc[i]    <- NA_integer_
  }
}

# checking few first values of approximation and difference
head(approx)
head(diff5)

# I am making final data frame for all results
pelldata <- data.frame(n=n, fib=fib, pell=pell, approx=approx, diff5=diff5, acc=acc)

# just checking first few rows
head(pelldata)

