Skip to content

Commit

Permalink
#1 - Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
obriensystems authored Jan 1, 2025
1 parent 3ed16b3 commit f65e5e0
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ The 3n+1, collatz or hailstone numbers problem - https://en.wikipedia.org/wiki/C
### Optimization 1: Combine odd/even steps
The following optimization will speed up a run by up to 21%

When we have an odd number, the next step is usually 3n + 1 applied to the current value. However, the number resulting from 3n + 1 will always be positive - which will require at least one divide by 2.
When we have an odd number, the next step is usually 3n + 1 applied to the current value. However, the number resulting from 3n + 1 will always be positive - which will require at least one divide by 2. If we combine the double step optimization with the fact that a shift right (or divide by 2) is always floor truncated (where the 1/2 is removed on an odd number). If we combine the floor with an implicit round up (ceil) by adding 1 (where for example 27 /2 = 13.5 = 13 rounded, with + 1 = 14) - we have the following math...

(3n + 1) / 2 = 3/2 * n + 1/2, where we drop the 1/2 due to rounding on a shift right. We then have 3/2 * n which is also n + n/2. We add 1 to this to get a round up (it will hold as we only perform this round up for odd numbers) - of - 1 + n + n/2.

The operation...
```
Expand All @@ -14,9 +16,9 @@ with a subsequent
n / 2 = n >> 1
```

can be expressed as a single
can be expressed as a single shift right with a add + 1 or effectively a divide by
```
n / 2 + n + 1 = n > 1 + n + 1
n / 2 + n + 1 = n >> 1 + n + 1
```
### Optimization 2: Roll up all divide by 2 sequences
When whe have for example a power of 2 like 256 - this will represent a straight path to 1 via 8 shift right operations.
Expand Down

0 comments on commit f65e5e0

Please sign in to comment.