Below are the solutions for Homework #1 for the R Bridge Course at CUNY SPS for the Data Science Master’s Program

Question 1:

factorial <- 12
result <- 1
if (factorial == 0){
  result = 1
}else {
  if(factorial < 0){
    result = "The factorial of a negative number cannot be calculated"
  }
  else {
    for (i in 1:factorial){
      result = result * i
    }
  }
}
print (result)
## [1] 479001600

Question 2:

x <- as.numeric(seq(20, 50, by =5))
print(x)
## [1] 20 25 30 35 40 45 50

Question 3:

quadratic = function(a, b ,c){
  if (is.numeric(a)&is.numeric(b)&is.numeric(c)){
    if (a==0){
      print("This is not a quadratic equation.")
    }else{
      ans1 <- (-b + sqrt(b^2 - (4*a*c)))/(2*a)
      ans2 <- (-b - sqrt(b^2 - (4*a*c)))/(2*a)
      if(is.nan(ans1)){
          print("There are no solutions")
        }else{
          if (ans1 == ans2){
            print("There is one solution and it is:")
            print(ans1)
          }else{
            print("Solution 1 is:")
            print(ans1)
            print("Solution 2 is:")
            print(ans2)
          }
        }
    }
  } else{
    print("Please enter valid numbers for the 3 inputs")
  }
}