The deposit pattern follows a simple rule: each day we deposit one more dollar than the previous day, but every Monday we reset to deposit one more dollar than we did on the previous Monday. We can simulate this process day by day, tracking when each week ends to reset the starting deposit for the new week.
1), and the total result.0 to n-1.1 (so week 1 starts with 1, week 2 starts with 2, etc.).Instead of simulating each day, we can use arithmetic series formulas. Each complete week deposits a fixed sum: week 1 deposits 1+2+3+4+5+6+7=28, week 2 deposits 2+3+4+5+6+7+8=35, and so on. The weekly sums form an arithmetic sequence with common difference 7. For the remaining days after complete weeks, we just add the deposits for those partial days.
n/7.28, and each subsequent week adds 7 more. Use the arithmetic series sum formula: weeks * (low + high) / 2, where low = 28 and high = 28 + 7 * (weeks - 1).n % 7), the Monday deposit is weeks + 1. Add the deposits for each remaining day (monday, monday+1, monday+2, ...).We can derive a closed-form formula using the sum of first k natural numbers: SUM(k) = k*(k+1)/2. Each week's extra contribution above the base week follows a pattern, and the remaining days also follow an arithmetic progression. This eliminates the loop needed for remaining days in the previous approach.
SUM(x) = x*(x+1)/2 which gives the sum of first x natural numbers.SUM(weeks-1) * 7 + weeks * SUM(7). This accounts for the increasing weekly base and the standard week pattern.SUM(n % 7) + weeks * (n % 7). This adds the base daily progression plus the offset from the current week.Each Monday starts with week_number dollars (week 1 starts with 1, week 2 starts with 2, etc.), not always 1. Forgetting to increment the Monday deposit each week gives incorrect totals.
# Wrong: always starting at 1
if day % 7 == 0:
deposit = 1 # Should be 1 + (day // 7)When computing complete weeks, using (n + 6) // 7 instead of n // 7 overcounts partial weeks as complete, leading to incorrect sums in the math-based approach.