---
# System prepended metadata

title: Mathematics
tags: [Data Structures & Algorithms, GeeksforGeeks]

---

# Mathematics

```
range(10) -> 0.... 9 
range(1,10) -> 1...9
range(1,10,2) -> 1,3,5,7,9
```


- Count digits

``` python
# TC: O(number of digits)
# SC: O(1)
def count_digits(n):
    result = 0
    while n > 0:
        n = n // 10
        result += 1
    return result 
```


- Palindrome number
![image](https://hackmd.io/_uploads/SyD3QooJC.png)

``` python
# TC: O(number of digits)
# SC: O(number of digits)
def is_palindrome(n):
    rev = str(n)[::-1] # reverse a string 
    if n == int(rev):
        return True
    return False
```

``` python
# TC: O(number of digits)
# SC: O(1)
def is_palindrome(n):
    rev = 0
    temp = n
    while temp > 0:
        last_digit = temp % 10
        rev = rev * 10 + last_digit
        temp = temp // 10
    return rev == n
```

- factorial

``` python
# TC: O(n)
# SC: O(1)
def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result 
```

- trailing zeros in factorial n
![image](https://hackmd.io/_uploads/Hk_zPQhkC.png)

``` python
# TC: O(n)
# SC: O(1)
def factorial_traling_zeros(n):
    fact = 1
    for i in range(1, n + 1):
        fact *= i
    result = 0
    while fact > 0:
        last_digit = fact % 10
        if last_digit != 0:
            break
        result += 1 
        fact = fact // 10
    return result 
```

``` python
# TC: O(log n)
# SC: O(1)
def factorial_traling_zeros(n):
    result = 0
    x = 5
    while x <= n:
        num_5 = n // x
        result += num_5
        x = x * 5
    return result 
```

- Greatest common divisor
greatest number that divides both numbers
![image](https://hackmd.io/_uploads/Sklb7V310.png)

``` python
# TC: O(min(a,b))
# SC: O(1)
def gcd(a, b):
    result = 1
    for x in range(2, min(a, b) + 1):
        if a % x == 0 and b % x == 0:
            result = x
    return result
```
