fork download
  1. #include <stdio.h>
  2.  
  3. #define TEST(x, y) printf("%d, %d => %d\n", (x), (y), common_root((x),(y)))
  4.  
  5. int common_root(int a, int b)
  6. {
  7. int temp;
  8.  
  9. if (a == 1 || b == 1)
  10. return -1;
  11. if (a == b) {
  12. return a;
  13. }
  14.  
  15. if (a > b) {
  16. // Swap to make sure a < b
  17. temp = a;
  18. a = b;
  19. b = temp;
  20. }
  21.  
  22. if ((b % a) == 0) // Check if `b` divisible by `a`
  23. return common_root(a, b/a);
  24. else
  25. return -1;
  26. }
  27.  
  28. int main(void) {
  29. TEST(1,2);
  30. TEST(2,3);
  31. TEST(6,10);
  32. TEST(4, 16);
  33. TEST(12, 24);
  34. TEST(27, 81);
  35. TEST(36, 1296);
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 5400KB
stdin
Standard input is empty
stdout
1, 2 => -1
2, 3 => -1
6, 10 => -1
4, 16 => 4
12, 24 => -1
27, 81 => 3
36, 1296 => 36