0

I'm currently attempting to work out the GCD of two numbers (x and y) in R. I'm not allowed to use loops or if, else, ifelse statements. So i'm restricted to logical and arithmetic operators. So far using the code below i've managed to make lists of the factors of x and y.

xfac<-1:x
xfac[x%%fac==0]

This gives me two lists of factors but i'm not sure where to go from here. Is there a way I can combine the common elements in the two lists and then return the greatest value?

Thanks in advance.

smci
  • 32,567
  • 20
  • 113
  • 146
Tyler Bell
  • 107
  • 2
  • 7

2 Answers2

1

Yes, max(intersect(xfac,yfac)) should give the gcd.

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
0

You have almost solved the problem. Let's take the example x <- 12 and y <- 18. The GCD is in this case 6.

We can start by creating vectors xf and yf containing the factor decomposition of each number, similar to the code you have shown:

xf <- (1:x)[!(x%%(1:x))] 
#> xf
#[1]  1  2  3  4  6 12
yf <- (1:y)[!(y%%(1:y))]
#> yf
#[1]  1  2  3  6  9 18

The parentheses after the negation operator ! are not necessary due to specific rules of operator precedence in R, but I think that they make the code clearer in this case (see fortunes::fortune(138)).

Once we have defined these vectors, we can extract the GCD with

max(xf[xf %in% yf])
#[1] 6

Or, equivalently,

max(yf[yf %in% xf])
#[1] 6
RHertel
  • 23,412
  • 5
  • 38
  • 64