How to deduce from an array of numbers divisible by the same number?
I understand how you can determine if two numbers are divisible by the same thing using Euclid's method. With array I do not understand how to do it.
is it a boolean answer? That is, is the question 'are all numbers in array divisible by 10' or is the question "which values in array are divisible by 10" or, worse, "what is the GCD of all the numbers in this array"?
If its the GCD of multiple numbers, I think I would sort the array from smallest to largest and get the prime factors of the smallest number, then check the largest of those against the rest of the array, for all the factors of the first one. But there may be a better way. Finding the factors of the numbers, if they are big enough, is an unholy problem (encryption theory is build around this hard problem). But if they are only 64 bit, it can still be done very quickly ... you 'only' have to check all the primes that fit in a 32 bit number, which is doable on a modern PC in very little time. And most numbers in range have less than 10 (distinct*) factors. You would have to sit down and theory at it a bit more than this... the GCD does not have to be prime... but the GCD will be some multiplication-combination of the prime factors of the first number (and repeats matter there...). Or you can look up the answer, but figuring it out would be more fun. If you look it up, the brute force way is: GCD(a,b,c,d) == GCD(GCD(GCD(a,b),c),d) .... but for a large array some subset will give you candidates to try on the rest, some sort of reduction like that will speed it up a lot... when a candidate fails the failure gives you a new candidate... which is what I was trying to do at the start of this ramble, but from the other side.
I sorted the array from smaller to larger. The answer must be a pair of numbers divisible by the same number. I used Euclid's method. I think you can find the divisor of the maximum number and then specify other numbers that are divisible by the same number.
#include <iostream>
int main()
{
int num {}, start {};
std::cout << "How many numbers:";
std::cin >> num;
std::cout << "Start number:";
std::cin >> start;
for (int d = 2; d < (num + start) / 2; ++d) {
std::cout << d << " : ";
for (int i = start; i <= start + num; ++i)
if (i % d == 0)
std::cout << i << " ";
std::cout << '\n';
}
}