I am curious to see if there is a nice way in R to prove that the formula P=n^2-2+41 for n=1,2,3,... is generating prime numbers (until 40)?
Nope. Check for n=1: (1^2) - 2 + 41 = 1 + 39 = 40. Not prime.
If you insist on using R code to check this, here's one way:
gen_p <- function(n) n^2 + 39
for(i in 1:40) print(gmp::isprime(gen_p(i)))
Let me also add that "demonstrating something works for many values of n" is not the same as proving it works generally for all values of n.