Add examples parallel_sum and sequential_sum

This commit is contained in:
Matt Joiner 2024-06-24 10:55:50 +10:00
parent d6ea0010c3
commit 6beb3d14fd
No known key found for this signature in database
GPG Key ID: 6B990B8185E7F782
2 changed files with 31 additions and 0 deletions

View File

@ -0,0 +1,17 @@
# Defines the function Sum with two parameters: start and target
def Sum(start, target):
if start == target:
# If the value of start is the same as target, returns start.
return start
else:
# If start is not equal to target, calculate the midpoint (half),
# then recursively call Sum on both halves.
half = (start + target) / 2
left = Sum(start, half) # (Start -> Half)
right = Sum(half + 1, target)
return left + right
# A parallelizable sum of numbers from 1 to 1000000
def main():
# This translates to (((1 + 2) + (3 + 4)) + ... (999999 + 1000000)...)
return Sum(1, 1_000_000)

View File

@ -0,0 +1,14 @@
# Defines the function Sum with two parameters: start and target
def Sum(start, target):
if start == target:
# If the value of start is the same as target, returns start.
return start
else:
# If start is not equal to target, recursively call Sum with
# start incremented by 1, and add the result to start.
return start + Sum(start + 1, target)
def main():
# This translates to (1 + (2 + (3 + (...... + (999999 + 1000000)))))
# Note that this will overflow the maximum value of a number in Bend
return Sum(1, 1_000_000)