简体   繁体   中英

Find all positive numbers divisible by 10 and less than n

I need to find all positive numbers that are divisible by 10 and less than n, i found a string with the same question but i have a hard time interpreting it as the user was using java so the codes are very different and confusing.

i tried to make a code by piecing together codes i've checked out but it only works if its divisible by other numbers, if its 10 it would keep going on forever with 0.

n = int(input("Enter a number: "))
x = 0
while x < n :    
    r = n % 10
    if r % 10 != 0 :
        x = x + r
print("positive numbers divisible by 10 ", x)

Below is simpler code which will help to get the list of numbers divisible by 10 and less than n:

n = int(input("Enter a number n: "))
divisibleBy10 = []
for i in range(0, n):
    if i % 10 == 0:
        divisibleBy10.append(i)

print(divisibleBy10)

You can do like this:

n = 100
i = 0
while i<n:
    if i%10==0:
        print(i)
    i+=1

This code below tries to reduce the number of loops. If 'x' is extremely large, it helps to optimize the solution. The idea is to not do the divisibility check for each number starting from 1 to n-1. Here, we use the fact that the least positive number divisible by 10 is 10. The next number of interest is 10 + 10 = 20, there by skipping numbers 11 to 19. This helps improve the performance.

x = input('Enter any number ')
y = 10
while y < x:
    print(y)
    y = y + 10

You can also try the following:

# grab the user's input
n = int(input('please enter a number: '))
# set x to 0, so the while loop can stop when 'n' is greater than '0'
x = 0
while n > x:
    if n % 10 == 0:
        print('{} is divisible by 10.'.format(n))
    n -= 1

So basically the loop enters with the value that the user inputs, let's say 10 .

  • Is 10 greater than 0 ? Yes (while loop executes), the if statement evaluates the remainder with the mod . The value is printed because the if statement evaluates True , the remainder is equal to zero. At last, n is subtracted by 1
  • Is 9 greater than 0 ? Yes (while loop executes), the if statement evaluates the remainder with the mod . The value is not printed because the if statement evaluates False , the remainder is not equal to zero. At last, n is subtracted by 1
  • Is 8 greater than 0 ? Yes (while loop executes), the if statement evaluates the remainder with the mod . The value is not printed because the if statement evaluates False , the remainder is not equal to zero. At last, n is subtracted by 1

...

And so on until n reaches 0 , the while loop stops because 0 is not greater than 0 .

我认为使用内联 for 循环:

print([i for i in range(10,n,10) if i % 4 == 0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM