Quantcast
Channel: Implement division using only addition - Code Golf Stack Exchange
Viewing all articles
Browse latest Browse all 18

Answer by plannapus for Implement division using only addition

$
0
0

R - 0 addition

divide<-function(a,b){    options(warn=-1)    A<-matrix(1:b,nrow=a,ncol=1)    length(split(A,A)[[b]])    }

Uses R vector recycling.
Second line creates a matrix of length a populated by a vector of length bwhich is recycled until reaching length a.
Third line split the matrix according to its value and return the length of the last element (hence the result of the integer division of a by b).
Populating a matrix with a vector which length is not a multiple of the length of the matrix throws a warning but if we suppress warning beforehand (line 1) it works.

To give a concrete example if we divide 5 by 3, A will be a vector containing 1 2 3 1 2 (i. e. 1 2 3 recycled to a length 5). The result of the splitting operation will be a list with the first element containing 1 1, the second 2 2 and the third 3 (since there is only one 3 in A). The result is therefore 1.


Viewing all articles
Browse latest Browse all 18

Trending Articles