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?
Your
to_intfunction isn't doing what you think.The expression
*input - '0'takes the character code of the first character ininputand subtracts the character code of'0'. So the result is the number corresponding to the first character of the given string, not the whole string.You need to perform this operation in a loop, multiplying the result by 10 before adding the value of the next digit.