Get a vector consisting of prime numbers as output from given input vector. Worked in Python, wherein I appended each prime number from the input list to an empty list, but not getting correct output in R
Python Code:
def get_prime(input_list):
output_list = []
for num in input_list:
for i in range(2, num):
if num%i == 0:
break
else:
output_list.append(num)
return output_list
Output:
get_prime([3,4,5,6,7,8])
[3, 5, 7]
R Code:
get_prime <- function(input_number_vector){
prime = c()
for(num in input_number_vector){
for(div in 2:(num-1)){ if(num %% div == 0) break
else prime = c(prime,num)
}
}
prime
}
Output:
x <- c(3,4,5,6,7,8)
> get_prime(x)
[1] 3 5 5 5 7 7 7 7 7
Expected Output:
3,5,7
Looks like the odd numbers: 3, 5, 7 are appended once for each modulus condition check. i.e. 3 once with divisor of 2, 5 thrice with divisors 2,3,4 and 7 with divisors 2,3,4,5,6. Could someone let me know where I am going wrong and if R works differently than Python in this regard.