epicours/Algo/B2/Exercises/Repetitive tutorial.md

109 lines
1.4 KiB
Markdown

## Exercise 1.1
```python
def zorglub(n: int) -> int:
j = 1
k = 0
i = 1
while i <= n:
j = i * j
k = j + k
i = i + 1
return k
```
The function return the sum of the factorial of n
## Exercise 1.2
```python
def multiplication(x: int, y: int) -> int:
result = 0
while y > 0:
m += x
y -= 1
return result
def multiplication2(x: int, y: int) -> int: # Thanks Hugo :p
if y < 0:
y = -y
if x < 0:
return multiplication(-x, y)
return -multiplication(x, y)
else
return multiplication(x, y)
def productZ(x, y):
pos = True
if x < 0:
x = -x
pos = False
if y < 0:
y = -y
pos = not pos
m = multiplication(x, y)
if not pos:
m = -m
return m
```
## Exercise 1.3
```
def exponetial(x: int, n: int) -> int:
result = 0
while n > 0:
m *= x
n -= 1
return result
def power(x, n):
if x == 0;
if n == 0:
raise Exception("0 power 0 undefinded")
else:
return 0
elif x == 1:
return 1
elif x == -1:
return (n%2)*(-2) + 1
else:
res = 1
while n > 0:
res *= x
n -= 1
return res
```
## Exercise 1.4
```python
def fibo(n: int) -> int:
a = 0
b = 1
c = 0
i = 2
while i <= n:
c = a + b
a = b
b = c
i += 1
return b
```
## Exercise 1.5
```python
def my_sum(n: int) -> int:
s = 0
i = 1
while i <= n:
s += u(i)
i += 1
return s
# OR
def my_sum(n: int) -> int:
s = 0
while n > 0:
s += u(n)
n -= 1
return s