Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the GCD without looping - R

So I'm trying to learn R and using a number of resources including a book called "Discovering Statistics using R" and a bunch of other cool eBooks.

I understand a great method in programming is the Euclid's Algorithm.

Implementing it in a loop can be achieved like this:

 gcd(x,y) //assuming x is the largest value
 //do
 r = x%y;
 x = y;
 y = r;
 //while r != 0;
 return x;

After several searches on Google, SO and Youtube refreshing my memory of gcd algorithms, I wasn't able to find one that doesn't use a loop. Even recursive methods seem to use loops.

How can this be achieved in R without the use of loops or if statements?

Thanks in advance.

like image 262
Reanimation Avatar asked Feb 01 '14 18:02

Reanimation


People also ask

How do you find gcd without loop?

gcd(x,y) //assuming x is the largest value //do r = x%y; x = y; y = r; //while r !=

How do you calculate gcd in R?

Example: Program to Find GCD In the function, we first determine the smaller of the two number since the H.C.F can only be less than or equal to the smallest number. We then use a for loop to go from 1 to that number. In each iteration we check if our number perfectly divides both the input numbers.

How do you calculate gcd manually?

If a and b are two numbers then the greatest common divisor of both the numbers is denoted by gcd(a, b). To find the gcd of numbers, we need to list all the factors of the numbers and find the largest common factor. Therefore, we can conclude that 4 is the highest common factor among all three numbers.


2 Answers

Reducing GCD for two integers enables you to compute GCD for any sequence of integers (sorted or not):

gcd2 <- function(a, b) {
  if (b == 0) a else Recall(b, a %% b)
}

gcd <- function(...) Reduce(gcd2, c(...))
like image 197
egnha Avatar answered Sep 28 '22 21:09

egnha


Using the statement "without loops or the if statement" literally, here is a recursive version that uses ifelse:

gcd <- function(x,y) {
  r <- x%%y;
  return(ifelse(r, gcd(y, r), y))
}

One might not expect it, but this is actually vectorized:

gcd(c(1000, 10), c(15, 10))
[1]  5 10

A solution using if would not handle vectors of length greater than 1.

like image 23
Matthew Lundberg Avatar answered Sep 28 '22 23:09

Matthew Lundberg