0

i have a set of five numbers numbers and i want to Write a function that finds a prime and non_prime numbers.The function Should write the non-prime number(s) factors.

Number_of_set <- c(89, 107, 597, 931, 1083)

the Result return by the function should be Like

#Prime numbers : 89 107 
#Non-prime numbers : 597 [3 199]  931 [7 7 19] 1083 [3 19 19] 

i tried this but the prime_factors do not return any numbers

prime_factors <- function(x, i=2, factors = NULL){
      if(x<i) factors
      else if(! x %% i) prime_factors(x/i, i, c(factors, i))
      else  prime_factors(x, i+1, factors)
}
Ifprime <- function(x){
     if(x == 2){
        print("Prime")
     }
     else if(all(x %% (2:(x-1)) != 0)){
        print("Prime")
     } 
     else {
        return(prime_factors(x))
     }
 }
for(i in seq_along(NumberSet)){
     Ifprime(NumberSet[i])
 }
  • If I run `prime_factors(12)` and `prime_factors(13)` it does return numbers. Perhaps you are missing a `print(Ifprime(NumberSet[i]))` in your `for`-loop? Depending on your expected output. – Martin Gal Dec 28 '22 at 10:49

1 Answers1

0

A few adjustments of your code should return your desired output:

Ifprime <- function(x){
  if(x == 2){
    print(paste(x, "is Prime"))
    return(NA_real_)
  }
  else if(all(x %% (2:(x-1)) != 0)){
    print(paste(x, "is Prime"))
    return(NA_real_)
  } 
  else {
    factors <- prime_factors(x)
    print(paste(x, "prime factors are", paste(factors, collapse = ", ")))
    factors
  }
}

output <- list()

output <- lapply(Number_of_set, Ifprime)
names(output) <- as.character(Number_of_set)

output

Now output is a list that looks like this:

$`89`
[1] NA

$`107`
[1] NA

$`597`
[1]   3 199

$`931`
[1]  7  7 19

$`1083`
[1]  3 19 19

An entry is a prime, iff the factors stored in the list are NA.

Martin Gal
  • 16,640
  • 5
  • 21
  • 39