0
n <- as.numeric(n)
b <- c()
for (i in 2:(n-1))
{ 
  a <-   (n%%i) 
  if (a==0) {
   b <-  print(i)
  }

}

ouput

 n <- readline(prompt = "Enter the value of n:")
Enter the value of n:10

> n <- as.numeric(n)

> b <- c()

> for (i in 2:(n-1))
+ { 
+   a <-   (n%%i) 
+   if (a==0) {
+    b <-  print(i)
+   }
+   
+ }
[1] 2
[1] 5

I want my output in vector form. I am not sure what to do.I ve tried this one method I saw in other answers but couldnt succeed .

2
  • 1
    b <- c(b,i) perhaps (instead of your line with print(b) in it)? Commented Oct 14, 2019 at 16:01
  • @AndrewGustar Thank you sir Commented Oct 14, 2019 at 17:42

2 Answers 2

3

if you want to store results inside b vector, try this example:

n <- 10
b <- c()

for (i in 2:(n-1)){ 
  a <-   (n%%i) 
  if (a==0) {
    b <- c(b, i)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

EDIT : (the previous code didn't fully retake your question)

You can also (ab)use the fact that %% as most base function is Vectorized :

n <- 10
result <- n %% 2:(n-1)
# to get index
which(result == 0)
#> [1] 1 4
# to get numbers
(2:(n-1))[which(result == 0)]
#> [1] 2 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.