ex00
c
int ft_iterative_factorial(int nb)
{
int num;
if (nb < 0)
return (0);
if (nb == 0)
return (1);
num = 1;
while (nb != 0)
{
num *= nb;
nb--;
}
return (num);
}
c
int ft_recursive_factorial(int nb)
{
if (nb < 0)
return (0);
if (nb == 0)
return (1);
else
return (nb * ft_recursive_factorial(nb - 1));
}
ex02
c
int ft_iterative_power(int nb, int power)
{
int ans;
if (nb == 0 && power == 0)
return (1);
else if (power < 0)
return (0);
else if (power == 0)
return (1);
ans = 1;
while (power != 0)
{
ans *= nb;
power--;
}
return (ans);
}
c
int ft_recursive_power(int nb, int power)
{
if (nb == 0 && power == 0)
return (1);
else if (power < 0)
return (0);
else if (power == 0)
return (1);
else
return (nb * ft_recursive_power(nb, power - 1));
}
ex04
c
int ft_fibonacci(int index)
{
if (index < 0)
return (-1);
else if (index == 0)
return (0);
else if (index == 1)
return (1);
else
return (ft_fibonacci(index - 1) + ft_fibonacci(index - 2));
}
ex05
c
int ft_sqrt(int nb)
{
long long i;
nb = (long long) nb;
if (nb < 1)
return (0);
if (nb == 1)
return (1);
i = 2;
while (i <= (nb / i))
{
if (i * i == nb)
return (i);
i++;
}
return (0);
}
ex06
c
int ft_is_prime(int nb)
{
int i;
if (nb <= 1)
return (0);
i = 2;
while (i <= (nb / i))
{
if (nb % i == 0)
return (0);
i++;
}
return (1);
}
ex07
c
int ft_is_prime(int nb)
{
int i;
if (nb <= 1)
return (0);
i = 2;
while (i <= (nb / i))
{
if (nb % i == 0)
return (0);
i++;
}
return (1);
}
int ft_find_next_prime(int nb)
{
long long x;
nb = (long long) nb;
if (nb <= 1)
return (2);
if (nb == 2147483647)
return (nb);
x = nb;
while (x <= nb * 2 || x <= 2147483647)
{
if (ft_is_prime(x) == 1)
return (x);
x++;
}
return (0);
}
ex08
c
#include <unistd.h>
int abs(int x)
{
if (x < 0)
return (-x);
return (x);
}
int find(char *row, int x)
{
int i;
i = 0;
while (i < 10)
{
if (row[x] == row[i] && x != i)
return (0);
else if (abs(row[x] - row[i]) == abs(x - i) && x != i)
return (0);
i++;
}
return (1);
}
void match_queen(char *row, int x, int *ans)
{
int i;
if (x == 10)
{
write(1, row, 10);
write(1, "\n", 1);
(*ans)++;
return ;
}
else
{
i = 0;
while (i < 10)
{
row[x] = i + '0';
if (find(row, x) == 1)
match_queen(row, x + 1, ans);
row[x] = -1;
i++;
}
return ;
}
}
int ft_ten_queens_puzzle(void)
{
int ans;
char row[10];
int x;
ans = 0;
x = 0;
while (x < 10)
{
row[x] = -1;
x++;
}
match_queen(row, 0, &ans);
return (ans);
}