ft_sqrt.c 598 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /* Create a function that returns the square root of a number (if it exists), or 0 if the
  2. square root is an irrational number.
  3. */
  4. #include <stdio.h>
  5. int ft_sqrt(int nb)
  6. {
  7. int i, max;
  8. i = 1;
  9. max = nb / 2;
  10. if (nb == 1 || nb == 0)
  11. {
  12. return (nb);
  13. }
  14. else if (nb < 1 || nb > 2147483647)
  15. {
  16. return (0);
  17. }
  18. while (i * i < nb && i <= max)
  19. {
  20. i++;
  21. if (i * i == nb)
  22. {
  23. return (i);
  24. }
  25. }
  26. return (0);
  27. }
  28. int main(void)
  29. {
  30. int a, b, c, d, e;
  31. a = ft_sqrt(-1);
  32. b = ft_sqrt(0);
  33. c = ft_sqrt(1);
  34. d = ft_sqrt(9);
  35. e = ft_sqrt(1600080001);
  36. printf("%d, %d, %d, %d, %d", a, b, c, d, e);
  37. }