|
| 1 | +## Development - Advanced, exercise 37 |
| 2 | + |
| 3 | +### Text |
| 4 | +**Trial division** is one of the integer factorisation algorithms. The idea is to see if an integer n greater than 1, provided as input, can be divided by each number in turn from 2 to n. For example: |
| 5 | + |
| 6 | +* for the integer *n = 12*, the list of factors dividing it is *2, 2, 3* (i.e. *12 = 2 * 2 * 3*); |
| 7 | +* for the integer *n = 11*, the list of factors dividing it is *11* (i.e. *11 = 11*, since 11 is prime andm thus, it can be divided by itself only); |
| 8 | +* for the integer *n = 15*, the list of factors dividing it is *3, 5* (i.e. *15 = 3 * 5*). |
| 9 | + |
| 10 | +The algorithm proceed by dividing the input number starting from the smallest possible number *f*, initially set to 2. If the division returns a reminder, it repeat the operation by incrementing f of one unit. Instead, if the division returns no reminder, *f* is added to the list of factors, and n will be assigned with the result of the division, before repeating the operation. For instance, considering *n = 18*, the initial *f = 2*, and the list of factors to return initially empty: |
| 11 | + |
| 12 | +1. 18 / 2 = 9 (with no remainder) → list of factors: 2; n = 9 |
| 13 | +2. 9 / 2 = 4 (with remainder 1) → f = 3 |
| 14 | +3. 9 / 3 = 3 (with no remainder) → list of factors: 2, 3; n = 3 |
| 15 | +4. 3 / 3 = 1 (with no reminder) → list of factors: 2, 3, 3; n = 1 |
| 16 | + |
| 17 | +The algorithm stop when *f* is greater than *n*, and returns the list of factors. |
| 18 | + |
| 19 | +Write an algorithm in Python – `def trial_div(n)` – which takes in input an integer `n` greater than 1, and returns the list with the factors dividing `n` according to the rules described above. |
| 20 | + |
| 21 | + |
| 22 | +### Solution |
| 23 | +```python |
| 24 | +# Test case for the function |
| 25 | +def test_trial_div(n, expected): |
| 26 | + result = trial_div(n) |
| 27 | + if result == expected: |
| 28 | + return True |
| 29 | + else: |
| 30 | + return False |
| 31 | + |
| 32 | + |
| 33 | +# Code of the function |
| 34 | +def trial_div(n): |
| 35 | + result = [] |
| 36 | + f = 2 |
| 37 | + |
| 38 | + while not f > n: |
| 39 | + if n % f == 0: |
| 40 | + result.append(f) |
| 41 | + n = n / f |
| 42 | + else: |
| 43 | + f = f + 1 |
| 44 | + |
| 45 | + return result |
| 46 | + |
| 47 | + |
| 48 | +# Tests |
| 49 | +print(test_trial_div(12, [2, 2, 3])) |
| 50 | +print(test_trial_div(11, [11])) |
| 51 | +print(test_trial_div(15, [3, 5])) |
| 52 | +print(test_trial_div(18, [2, 3, 3])) |
| 53 | +``` |
| 54 | + |
| 55 | +### Additional material |
| 56 | +The runnable [Python file](exercise_37.py) is available online. |
0 commit comments