I'm trying to write a program which updates the smallest number of an array by itself iteratively until all the numbers in the array are the same (an algorithm for finding the lcm). My program seems to end up in an endless loop. My guess is that it is caused by are_same()
returning always zero caused by something in get_min_index()
and/or divisors[min_index] += divisors[min_index]
. I'm wondering if this has to do with some C-language peculiarity I'm not aware of. Could some experienced C programmer help me out with this?
#include <stdio.h>
int are_same(int array[], int length) {
for (int i = 1; i < length; i++) {
if (array[0] != array[i]) {
return 0;
}
}
return 1;
}
int get_min_index(int array[], int length) {
int min_value = array[0];
int min_index = 0;
for (int i = 1; i < length; i++) {
if (array[i] < min_value) {
min_value = array[i];
min_index = i;
}
}
return (min_index);
}
int main(void) {
int divisors[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int length = sizeof(divisors) / sizeof(divisors[0]);
int min_index;
do {
min_index = get_min_index(divisors, length);
divisors[min_index] += divisors[min_index];
} while (are_same(divisors, length) == 0);
printf("lcm=%d", divisors[0]);
return(0);
}