-3

I have a number, let, 17. I want to randomly break it into two parts, in such a way that sum of these parts give the result 17. Eg. 13 + 4, 12 + 5...But I also want that these two parts must not have 2 as a number. Any algorithm or code in Python. Please help.

Abhishek Singh
  • 1
  • 1
  • 1
  • 4

1 Answers1

1

Use random.randint() to generate the first number and then subtract it from n, we got the second number. The if else statement make sure neither of num1 and num2 is equal to 2. Hope this is helping!

import random

def break_num(n):

    while True:

        num1 = random.randint(1, n - 1)
        num2 = n - num1

        if num1 != 2 and num2 != 2:
            break
        else:
            continue

    print(f'{num1} + {num2}')
Jimmy Lin
  • 44
  • 4