|
1 |
| -function! Square(number) abort |
2 |
| - if a:number < 1 || a:number > 64 |
3 |
| - throw 'square must be between 1 and 64' |
4 |
| - endif |
| 1 | +" Helper function to add two numbers represented as strings |
| 2 | +function! StringAdd(num1, num2) |
| 3 | + let carry = 0 |
| 4 | + let result = '' |
5 | 5 |
|
6 |
| - return float2nr(pow(2, (a:number-1))) |
| 6 | + " Pad the shorter number with leading zeros |
| 7 | + let len1 = strlen(a:num1) |
| 8 | + let len2 = strlen(a:num2) |
| 9 | + if len1 < len2 |
| 10 | + let a:num1 = repeat('0', len2 - len1) . a:num1 |
| 11 | + elseif len2 < len1 |
| 12 | + let a:num2 = repeat('0', len1 - len2) . a:num2 |
| 13 | + endif |
| 14 | + |
| 15 | + " Add digits from right to left |
| 16 | + for i in range(strlen(a:num1) - 1, 0, -1) |
| 17 | + let sum = str2nr(a:num1[i]) + str2nr(a:num2[i]) + carry |
| 18 | + let carry = sum >= 10 ? 1 : 0 |
| 19 | + let result = string(sum % 10) . result |
| 20 | + endfor |
| 21 | + |
| 22 | + " Add the last carry if it exists |
| 23 | + if carry > 0 |
| 24 | + let result = '1' . result |
| 25 | + endif |
| 26 | + |
| 27 | + return result |
7 | 28 | endfunction
|
8 | 29 |
|
9 |
| -function! Total() abort |
10 |
| - return float2nr(pow(2, 64) - 1) |
| 30 | +" Function to calculate grains on a specific square using string manipulation |
| 31 | +function! Square(n) |
| 32 | + if a:n < 1 || a:n > 64 |
| 33 | + throw 'square must be between 1 and 64' |
| 34 | + endif |
| 35 | + |
| 36 | + " Start with 1 grain on the first square |
| 37 | + let grains = '1' |
| 38 | + for i in range(2, a:n) |
| 39 | + " Double the grains by adding it to itself |
| 40 | + let grains = StringAdd(grains, grains) |
| 41 | + endfor |
| 42 | + |
| 43 | + return grains |
| 44 | +endfunction |
| 45 | + |
| 46 | +" Function to calculate the total grains on the chessboard using string manipulation |
| 47 | +function! Total() |
| 48 | + let total = '0' |
| 49 | + |
| 50 | + " Accumulate grains for each square from 1 to 64 |
| 51 | + let grains = '1' |
| 52 | + for i in range(1, 64) |
| 53 | + let total = StringAdd(total, grains) |
| 54 | + " Double grains for the next square |
| 55 | + let grains = StringAdd(grains, grains) |
| 56 | + endfor |
| 57 | + |
| 58 | + return total |
11 | 59 | endfunction
|
0 commit comments