GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Math/odd_sum.py at master · zone0119/coding-problems Expand file tree/ Copy pathodd_sum.pyMore file actions 48 lines (39 loc) · 1.18 KB / Copy pathodd_sum.pyFile metadata and controls48 lines (39 loc) · 1.18 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 ''' Odd Sum For a given range [а,b], find the sum of all odd numbers between a and b. Input: 3, 9 Output: 24 Output explanation: 3+5+7+9=24 ========================================= Several different O(1) approaches exist. This is the explanation of my solution/formula. 3 + 5 + 7 + 9 can be written like (3 + 0) + (3 + 2) + (3 + 4) + (3 + 6) that's (3 * 4) + (2 + 4 + 6), also this can be written like (3 * 4) + ((2 * 1) + (2 * 2) + (2 * 3)) = 3 * 4 + 2 * (1 + 2 + 3) And the formula is: Min_Odd * Num_Odds + 2 * Sum(Num_Odds) Sum formula is N*(N-1)/2. (for all numbers smaller than N) This is the simplest formula: Min_Odd * Num_Odds + 2 * Num_Odds * (Num_Odds - 1) / 2 = Num_Odds * (Min_Odd + Num_Odds - 1) Time Complexity: O(1) Space Complexity: O(1) ''' ############ # Solution # ############ def odd_sum(a, b): # find first odd number if a % 2 == 0: a += 1 # to avoid rounding (math.ceil) find the biggest even number if b % 2 == 1: b += 1 # count of odd numbers n = (b - a + 1) // 2 # use the formula from the description return n * (a + n - 1) ########### # Testing # ########### # Test 1 # Correct result => 24 print(odd_sum(3, 9)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |