Skip to content

Instantly share code, notes, and snippets.

@nhtranngoc
Last active August 6, 2020 03:29
Show Gist options
  • Save nhtranngoc/ffc9d22835afe95c7ca70e546007cb54 to your computer and use it in GitHub Desktop.
Save nhtranngoc/ffc9d22835afe95c7ca70e546007cb54 to your computer and use it in GitHub Desktop.
Program to check if input numbers are Pythagorean triplets.
// Written by Nam Tran Ngoc
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned int a, b, c;
printf("Please enter three positive integers as sides of a triangle, separated between spaces: \n");
scanf("%d %d %d", &a, &b, &c);
// Since a, b, c are unsigned, they can't be negatives, so you only have to check if they exceed the bounds.
if(a <= 1000 && b <= 1000 && c <= 1000) {
if(a*a + b*b == c*c || b*b + c*c == a*a || c*c + a*a == b*b) {
printf("Yes.\n");
} else {
printf("No.\n");
}
} else {
printf("The lengths are too great\n");
// Return 1 to indicate error.
return 1;
}
return 0;
}
@nhtranngoc
Copy link
Author

nhtranngoc commented Aug 6, 2020

Alternatively:

if ( (a > 0 && a <= 1000) &&
   ( (b > 0 && b <= 1000) &&
   ( (c > 0 && c <= 1000)) {

    ...
}

@nhtranngoc
Copy link
Author

Or, better yet:

int is_within_bounds(int x, int lower, int upper) {
  if (x >= lower && x <= upper) {
    return 1;
  } else return 0;
}

...

if (is_within_bounds(a, 0, 1000) && is_within_bounds(b, 0, 1000) && is_within_bounds(c, 0, 1000) {
  ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment