Some 3-dimensional non-coprime vectors include: $x = [2,4,6] ,[0, 10, 15] ,[0, 12, 12]$ For fixed $N$ and $K$, my set contains a total of $(2K+1)^N$ distinct integer vectors as each of the $N$ elements can take on integer values from $-K,ldots,0,ldots,K$. A brute-force approach for counting the number of coprime vectors consists of iterating over each of the $(2K+1)^N$ possible vectors and checking to see whether they are coprime (using, for instance, this function). Unfortunately, this approach quickly runs into time and memory issues for large values of $N$ and $K$. I am wondering if anyone can think of a way to smart algorithm to do this. Ideally, I am looking to implement this algorithm as a MATLAB function that can number of coprime pairs given $N$ and $K$ as its input.
Asked By : Berk U.
Answered By : D.W.
- $gcd(x_1,x_2,x_3)=1$ iff either (a) $gcd(x_1,x_2)=1$, or (b) $gcd(x_1,x_2)>1$ (so define $d=gcd(x_1,x_2)$) and $gcd(d,x_3)=1$.
These two conditions are mutually exclusive, so you can count the number of type-(a) triples and the number of type-(b) triples and then sum those two numbers, to get the number of co-prime triples. You can count the number of triples of type-(a) quickly (by reducing to the $N=2$ case). You can also count the number of triples of type-(b) quickly, by summing over all possible values of $d$ (for fixed $d$, the number of type-(b) tuples with a particular value of $d$ reduces to a smaller version of your problem with $N=2$ and a smaller value of $K$). I think you can probably see how to generalize this to larger $N$, giving you a recursive algorithm to solve your problem for general $N$. I’ll let you work out the details.
Best Answer from StackOverflow
Question Source : http://cs.stackexchange.com/questions/18552