So I am having problems printing my prime numbers using R. This is my code so far:
Problem: Write a R code to print all prime numbers less than x=20. Your code must also work for any other integer.
prime = 0:50
temp = 0
for(val in prime){
if (val == 0){
next
} else if (val == 1){
next
} else if (val == 2){
TRUE
temp = val
} else if (val %% temp == 0){
next
temp = temp + 1
}
print(val)
}
It keeps listing the following numbers:
[1] 2
[1] 3
[1] 5
[1] 7
[1] 9
[1] 11
[1] 13
[1] 15
[1] 17
[1] 19
[1] 21
[1] 23
[1] 25
[1] 27
[1] 29
[1] 31
[1] 33
[1] 35
[1] 37
[1] 39
[1] 41
[1] 43
[1] 45
[1] 47
[1] 49
As we can see, 9, 15, 21, 25, 27, etc... are not prime and I don't know how to fix this. My class just started learning about for loops and if/else statements so please nothing too fancy.