[Solved] How to divided number into three continuous parts such that the third part is the sum of the other two? [closed]


Here’s my solution, it checks all possible combinations of splitting given number in 3 parts and checks whether sum of first two components are equal the third one.

def correct_number(x):
    str_nmbr = str(x)
    for result_split in range(len(str_nmbr)-2):
        part_3 = int(str_nmbr[-result_split-1:])

        for components_split in range(len(str_nmbr)-2-result_split):
            part_2 = int(str_nmbr[1+components_split: -result_split-1])
            part_1 = int(str_nmbr[:components_split+1])

            if part_1 + part_2 == part_3:
                return True

    return False

print(correct_number(9999198)) # True

As author requested here’s visual explanation how determining parts for number works, given number “1234567”

1 2 3 4 5 6 7:

  • First loop chooses second separator
  • 1 2 3 4 5 6|7
  • Second loop chooses first one
  • 1 2|3 4 5 6|7
  • 1 2 3|4 5 6|7
  • 1 2 3 4|5 6|7
  • 1 2 3 4 5|6|7
  • . . . Then we move second second separator 1 step back
  • 1 2 3 4 5|6 7
  • And we continue on moving first separator
  • 1|2 3 4 5|6 7
  • 1 2|3 4 5|6 7
  • 1 2 3|4 5|6 7
  • . . .

3

solved How to divided number into three continuous parts such that the third part is the sum of the other two? [closed]