Search code examples
pythonconcatenationdivision

Concatenate the numbers between 1 and N and see if it is divisible by 3


I'm trying to make a program that basically works like this: I ask for a number, and from that number I must form a number N by concatenating all the numbers between 1 and N. For example, if I enter a 12, the number N will be 123456789101112, or if I enter a 6, the number would be 123456. Once N has been formed, I must return "YES" on the screen in the case that N is divisible by 3 and “NO” in the case that it is not.

This is what I have:

n = int(input("Enter a number:"))

for x in range (n + 1):
if(n%3==0):
    print("YES")
else:
    print("NO")

I just started using Python and I don't know what I'm doing wrong, if someone can give me a hand I would be very grateful!


Solution

  • If you want to do it using the algorithm you describe, then a simple (but not very fast) way of doing it would be so:

    n = int(input("Enter a number:"))    # get the number
    
    stringNumber = ""
    for x in range(1, n+1):
      stringNumber += str(x)             # join the string version of numbers 1...n into a string
    
    intNumber = int(stringNumber)        # convert the string concatenation into an int
    
    if (intNumber % 3 == 0):             # check if the int is divisible by 3
        print("YES")
    else:
        print("NO")
    

    You can speed-up the string concatenation by using join() if you wish:

    stringNumber = "".join([str(digit) for digit in range(1,n+1)])
    

    the result is the same

    However, you might also notice that a number is divisible by 3 if the sum of its digits is divisible by 3, so you can use an algorithm like this:

    n = int(input("Enter a number:"))    # get the number
    
    sumOfDigits = sum([digit for digit in range(1,n+1)])   # sum numbers 1...n
    
    if (sumOfDigits % 3 == 0):             # check if the int is divisible by 3
        print("YES")
    else:
        print("NO")