0

I am looking to write a function that accepts 2 arguments.

  1. A single positive integer, "n"
  2. A logical indicator, "all"

The function should do the following:

If TRUE, return the first n prime numbers as a single vector.
ELSE return only the n-th prime number.

The output should be:

genprime(7, all=TRUE)

[1] 2 3 5 7 11 13 17

 genprime(7, all=FALSE)

[1] 17

Hector Haffenden
  • 1,360
  • 10
  • 25
Rizan
  • 11
  • 2
  • 4
    Please show what steps you have taken to create your function so far. – Mike Mar 25 '19 at 18:23
  • 1
    Hi, welcome to Stackoverflow. We're here to help you with code that you wrote. We're not here to write code for you. – RolfBly Mar 25 '19 at 19:12

1 Answers1

0

Let me help you in putting the structure in place with below sample code:

generateFirstN_primesNumbers <- function(x) {
  #This function returns first x primes numbers
  # DO SOME WORK
  return(finalvector)
}

genprime <- function(n, all = TRUE) {
  allPrimes <-  generateFirstN_primesNumbers(n)
  if (all) {
    allPrimes  
  } else {
    allPrimes[length(allPrimes)]
  }
}

You still need to work on generateFirstN_primesNumbers function which will take x and return first X prime numbers.

Sonny
  • 3,083
  • 1
  • 11
  • 19