Functions f(n) and g(n) are defined below as:

n(4n-1)(4n-2)(f(n)-f(n-1)) = 1 , f(1) = 1/6

n(4n+1)(4n+2)(g(n)-g(n-1)) = 1 , g(1) = 1/30

By writing code or otherwise compute:

F = f(2024) and G = g(2024)

What is F + 3 - G?

I’ll start with an example of how to solve this using a vector. This can be useful in cases where you may want to inspect the intermediate values, or if you need to reference earlier computed values in a more complex recurrence relation than this.

Only base R is required for the below:

# First, construct a function to compute f(n):
compute_f <- function(n) {
  f_values <- numeric(n)
  f_values[1] <- 1/6
  for (i in 2:n) {
    f_values[i] <- f_values[i-1] + 1 / (i * (4*i - 1) * (4*i - 2))
  }
  return(f_values[n])
}

# Then, construct a function to compute g(n):
compute_g <- function(n) {
  g_values <- numeric(n)
  g_values[1] <- 1/30
  for (i in 2:n) {
    g_values[i] <- g_values[i-1] + 1 / (i * (4*i + 1) * (4*i + 2))
  }
  return(g_values[n])
}

# Next, calculate f(2024) and g(2024):
F_2024 <- compute_f(2024)
G_2024 <- compute_g(2024)

# Finally, we calculate F + 3 - G for 2024:
result <- F_2024 + 3 - G_2024
result
## [1] 3.141593
# The result is Pi!

This solution uses a for loop to iterate from 2 up to n, starting at 2 since 1 is given and does not need to be computed, incrementally building up the values of f and g based on the recurrence relations provided.

It then computes F_2024 and G_2024 by calling these functions with the argument 2024, allowing us to finally calculate F_2024 + 3 - G_2024.

Alternatively, you can solve this brainteaser using a single variable to hold the last computed value and update it in every step of the loop as below:

# Construct a function that will return only the last value of f:
compute_f <- function(n) {
  last_f <- 1/6  
  for (i in 2:n) {
    last_f <- last_f + 1 / (i * (4*i - 1) * (4*i - 2))
  }
  return(last_f)
}

# Construct a function that will return only the last value of g:
compute_g <- function(n) {
  last_g <- 1/30  
  for (i in 2:n) {
    last_g <- last_g + 1 / (i * (4*i + 1) * (4*i + 2))
  }
  return(last_g)
}

# Calculate f(2024) and g(2024):
F_2024 <- compute_f(2024)
G_2024 <- compute_g(2024)

# Calculate F + 3 - G for 2024:
result2 <- F_2024 + 3 - G_2024
result2
## [1] 3.141593

Happy Pi Day, friends!