R Program to find the sum of prime numbers between 1 to n


In this program, You will learn how to find the sum of prime numbers between 1 to n in R.


Prime numbers: 2, 3, 5, 7, 11, 13, 17, 19

Sum of Prime numbers: 2 + 3 = 5

Example: How to find the sum of prime numbers between 1 to n in R

{
    n = as.integer(readline(prompt = "Enter a number :"))
    s=0

    for (j in 2:n) {
      f = 1
      i = 2
      n = j
      while (i <= n / 2) {
        if (n %% i == 0) {
          f = 0
          break
        }
        i = i + 1
      }

      if (f == 1) {
        s=s+n
      }
    }
    print(paste("The sum of all prime 1 to n :",s))
}

Output:

Enter a number :4
[1] "The sum of all prime 1 to n : 5"