65 lines
1.7 KiB
C
65 lines
1.7 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_sqrt.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: tosuman </var/spool/mail/tosuman> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2023/03/30 01:42:42 by tosuman #+# #+# */
|
|
/* Updated: 2023/03/30 01:42:45 by tosuman ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#define INT_MAX_SQRT 46340
|
|
|
|
int ft_sqrt(int nb)
|
|
{
|
|
int sqrt;
|
|
int old_sqrt;
|
|
int max;
|
|
int min;
|
|
|
|
min = 0;
|
|
max = nb;
|
|
if (nb > INT_MAX_SQRT)
|
|
max = INT_MAX_SQRT;
|
|
sqrt = max;
|
|
while (1)
|
|
{
|
|
old_sqrt = sqrt;
|
|
if (sqrt * sqrt == nb)
|
|
return (sqrt);
|
|
if (sqrt * sqrt > nb)
|
|
max = sqrt;
|
|
if (sqrt * sqrt < nb)
|
|
min = sqrt;
|
|
sqrt = (max + min) / 2;
|
|
if (sqrt == old_sqrt)
|
|
break ;
|
|
}
|
|
return (0);
|
|
}
|
|
|
|
/* ////
|
|
#include <stdio.h>
|
|
#include <limits.h>
|
|
|
|
int main(void)
|
|
{
|
|
int i;
|
|
|
|
printf("%d, %d\n", 0, ft_sqrt(0));
|
|
i = -20;
|
|
while (++i <= 4000)
|
|
if (ft_sqrt(i))
|
|
printf("%d, %d\n", i, ft_sqrt(i));
|
|
printf("%d, %d\n", INT_MIN, ft_sqrt(INT_MIN));
|
|
printf("%d, %d\n", INT_MAX, ft_sqrt(INT_MAX));
|
|
i = INT_MAX;
|
|
while (--i > INT_MAX - 1000000)
|
|
if (ft_sqrt(i))
|
|
printf("%d, %d\n", i, ft_sqrt(i));
|
|
return (0);
|
|
}
|
|
*/ ////
|