Here's a program i wrote to find the greatest common divisor of two numbers. I was required by the teacher to use for loops.
The output screen displayed "Enter two numbers:" and I entered 45 and 15 expecting an answer of 15 but I got "gcd is 225". Can someone please tell me what's wrong with the program?
Euclid's algorithm needs a single loop, it doesn't use multiplication, and it only needs a single extra variable, certainly not arrays. So I don't know what you did there.
I created two arrays with loops to find the divisors of the numbers. Then I check the largest number of the first array with the other numbers of the second array , in case of matching it enters the if else and gets stored into gcd . And then it goes back to the outer loop and takes the next number of the first array and repeats the process.for an example like 45 and 15 the arrays should contain 1 3 5 15 45 and 1 3 5 15. The matching happens thrice so maybe I should put an exit function after the if?
This is massively inefficient in both time and space. Also, 30 divisors is nowhere near enough for even modestly large numbers. 2310 (the product of the first five primes) has 32 divisors. Even in the "list all common divisors and keep the largest" style of naïve algorithms, there are better ways to do this.
The problem in you code is that you're multiplying gdc by the matching array elements. This would only be appropriate if you were storing prime factors in the arrays, not divisors.