fork(1) download
  1. #include <iostream>
  2. #include <exception>
  3. #include <stdexcept>
  4.  
  5. int gcd(int a, int b) {
  6. if(a<0 || b<0) {
  7. throw std::invalid_argument("a and b must be negative values");
  8. }
  9. if(a==0 || b==0)
  10. return a+b;
  11. while(a!=b) {
  12. if(a>b) {
  13. a = a - b;
  14. }
  15. else {
  16. b = b - a;
  17. }
  18. }
  19. return a;
  20. }
  21.  
  22. #define expect_true(arg) \
  23.   do { \
  24.   if(!(arg)) { \
  25.   std::cout << "Unexpected false at " \
  26.   << __FILE__ << ", " << __LINE__ << ", " << __func__ << ": " << #arg \
  27.   << std::endl; } \
  28.   } while(false);
  29.  
  30. void test_gcd() {
  31. expect_true(gcd(16,24) == 8);
  32. expect_true(gcd(0, 19) == 19);
  33. bool exceptionCaught = false;
  34. try {
  35. gcd(5, -15);
  36. } catch (const std::invalid_argument& ex) {
  37. std::cout << "Illegal as expected" << std::endl;
  38. exceptionCaught = true;
  39. }
  40. expect_true(exceptionCaught);
  41. }
  42.  
  43. int main() {
  44. test_gcd();
  45. return 0;
  46. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
Illegal as expected