I have written the following program that takes two numbers from the command line and returns the gcd of these numbers.
#include <stdio.h>
int to_int(char *input)
{
return *input - '0';
}
int main(int argc, char *argv[])
{
if (argc < 2) return 1;
int a = to_int(argv[1]);
int b = to_int(argv[2]);
int i;
int result;
for (i = 1; i <= a && i <= b; i++) {
if (a%i==0 && b%i==0) {
result = i;
}
}
printf("%d\n", result);
return 0;
}
However when I give it the numbers 4 and 16 it returns the answer 1. This is incorrect. The gcd of 4 and 16 is 4. However I cannot find what is wrong with my code. Other examples that I found on the internet seem to be using the same algorithm that I am using (test if both numbers are evenly divisable by i and if they are then the gcd is i).
Could somebody point me towards the mistake in my code?