Find all positive numbers divisible by 10 and less than n - python

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

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.

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

I think use inline for loop:
print([i for i in range(10,n,10) if i % 4 == 0])

Related

Print all perfect numbers less than N

I am trying to print all perfect numbers lesser than an integer, but I am not sure how to do it. Could you help me, please? When I execute the code, it writes ValueError: invalid literal for int() with base 10.
My code:
n = input()
w = int(n) - 1
i = 0
a = 0
z = 0
list = []
for w in range(w, 1):
for i in range(w, 2):
if w % i == 0:
a = int(w / i)
z = z + a
if z == w:
list.append(w)
print(list)
What is a perfect number?
In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself.
Here's how you can do it:
n = input('Enter the integer:')
w = int(n) - 1
l = [] # creating an empty list 'l'
for i in range(w, 0, -1): # Runs the loop for all integers below n and greater than 0.
s = 0 # Set the sum to 0.
for j in range(i,0, -1): # Runs the loop till 0 to check for all divisors
if i % j == 0 and j!= i: # If the number is a divisor of 'i' and not equal to the 'i' itself.
s = s + j # Then add the divisor to the sum
if s == i: # If sum is equal to the number 'i'
l.append(i) # Then add the number 'i' to the list 'l'
print(l)
Output:
Enter the integer:10000
[8128, 496, 28, 6]
What you were doing wrong?
Naming a list by a Python keyword is a bad practice and should be avoided! You named the list by the name list which is a keyword in Python.
You were using the same variable names for different tasks such as w for denoting integer less than n and also range in for loop. This should be avoided too!
Idk, why you were using the variable a but there's no need to initialize variables with 0 if you are using as range in for loop.
You were running the for loop till 1 instead should run it 0.
You were not setting the sum to zero at every integer.
Here is a very simple implementation of the perfect numbers algorithm:
def isperfect(n: int) -> bool:
"""Test if a number is perfect."""
sum_ = sum(i for i in range(1, n//2+1) if not n % i)
return sum_ == n
n = int(input('Enter a positive integer: '))
p = [i for i in range(1, n) if isperfect(i)]
Output:
Enter a positive integer: 10000
print('Perfect numbers:', *p)
Perfect numbers: 6 28 496 8128
Explanation:
The isperfect function is used to test whether n is perfect. Efficiency is gained by only testing numbers <= n/2.
Capture the user's requested integer.
Using list comprehension, iterate the range of values (N-1) and test if each is perfect.
The perfect numbers are captured and stored into the p variable as a list.

Python gives empty list when change loop range

hi everyone i have a problem with my codes below. as you can see i am trying to find "near power sum" numbers(35---> 3^2 + 5^2 = 34) when i arrange my range 10 to 100 program gives the exact results 35 and 75. however when i change the range like 100000 to 500000 or 1000000 it gives nothing, just an empty list. could you please help me about this?
import math
mylist=[]
for i in range(100000,1000000):
a =0
b=0
num=i
while num >= 1:
b = num%10
a= a+(b**2)
num = math.trunc(num/10)
if a == i-1 or a== i+1:
mylist.append(i)
print(mylist)
Numbers from your new range have only 5 digits. The biggest "near power sum" you can get in that range will be 9^2 * 5 = 405 which is less than your lower boundary 1e+5. So your code works properly as there is no way your condition can be satisfied for that range.
Let us take a decimal number with n digits n>2. I will assume that it has no leading 0, so its first digit is >=1.
Then the number is >= 10**(n-1)
Its digits are at most 9 so the sum of the square of its digits is <= n*81
For n =4, the number is >=1000 while the sum of the square of its digits is < 4*81 = 324: no deal...
And it will be worse when n increases.

Where does the 3 in my prime number list get appended?

I can understand how every other prime number after 3 gets appended because (x%y != 0) but for the first iteration of the for loop it seems that x%y would equal 0. So how does it end up getting appended to my prime list?
def count_primes(num):
# edge case: 1 and 0 are not prime numbers
if num < 2:
return 0
# create prime list, check length to find amount of primes up to input num
# insert 2 bc it is only even prime number. Allows use of step in range to only iterate odds
primes = [2]
# create variable that holds prime candidates starting after 2
x = 3
# proceed into loop if prime candidate is less than or equal to input number
while x <= num:
# cycle through odd numbers up to input number
for y in range(3,x,2):
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
return primes
When x is 3, range(3,x,2) is an empty range - so no % test gets done for that number.
– jasonharper's comment

Why does this code not go to an infinite loop? (Python)

I'm currently beginning to learn Python specifically the while and for loops.
I expected the below code to go into an infinite loop, but it does not. Can anyone explain?
N = int(input("Enter N: "))
number = 1
count = 0
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
For this code to not infinitely loop, count needs to be >= N.
For count to increase, x needs to be equal to 2.
For x to be equal to 2 the inner for loop needs to run twice:
for i in range(1, number+1):
if number % i == 0:
x = x + 1
For the inner for loop to run twice number must not have factors besides 1 and the number itself. This leaves only prime numbers.
The inner loop will always set x == 2 when number is a prime number. As there are an infinite amount of prime numbers, count >= N will eventually be satisfied.
Try to change N to number:
while count < N:
while count < number:
Ok let's dissect your code.
N = int(input("Enter N: "))
number = 1
count = 0
Here you are taking user input and setting N to some number,
for the sake of brevity let's say 4. It gets casted as an int so it's now
an integer. You also initialize a count to 0 for looping and a number variable holding value 1.
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
Here you say while count is less than N keep doing the chunk of code indented.
So in our N input case (4) we loop through until count is equal to 4 which breaks the logic of the while loop. Your first iteration there's an x = 0 this means everytime you start again from the top x becomes 0. Next you enter a for loop going from 1 up to but not including your number (1) + 1 more to make 2. you then check if the number is divisible by whatever i equals in the for loop and whenever that happens you add 1 to x. After iteration happens you then check if x is 2, which is true and so you enter the if block after the for loop. Everytime you hit that second if block you update count by adding one to it. now keep in mind it'll keep updating so long as that if x == 2 is met and it will be met throughout each iteration so eventually your while loop will break because of that. Hence why it doesn't go forever.

How can I Keep the following program running until it becomes a single digit number?

I want to write a program that can calculate the sum of an integer as well as count its digits . It will keep doing this until it becomes a one digit number.
For example, if I input 453 then its sum will be 12 and digit 3.
Then it will calculate the sum of 12=1+2=3 it will keep doing this until it becomes one digit. I did the first part but i could not able to run it continuously using While . any help will be appreciated.
def main():
Sum = 0
m = 0
n = input("Please enter an interger: ")
numList = list(n)
count = len(numList)
for i in numList:
m = int(i)
Sum = m+Sum
print(Sum)
print(count)
main()
It is not the most efficient way, but it doesn't matter much here; to me, this is a problem to elegantly solve by recursion :)
def sum_digits(n):
n = str(n)
if int(n) < 10:
return n
else:
count = 0
for c in n:
count += int(c)
return sum_digits(count)
print sum_digits(123456789) # --> 9 # a string
A little harder to read:
def sum_digits2(n):
if n < 10:
return n
else:
return sum_digits2(sum(int(c) for c in str(n))) # this one returns an int
There are a couple of tricky things to watch out for. Hopefully this code gets you going in the right direction. You need to have a conditional for while on the number of digits remaining in your sum. The other thing is that you need to covert back and forth between strings and ints. I have fixed the while loop here, but the string <-> int problem remains. Good luck!
def main():
count = 9999
Sum = 0
m = 0
n = input("Please enter an integer: ")
numList = list(n)
while count > 1:
count = len(numList)
for i in numList:
m = int(i)
Sum = m+Sum
print(Sum)
print(count)
# The following needs to be filled in.
numlist = ???
main()
You can do this without repeated string parsing:
import math
x = 105 # or get from int(input(...))
count = 1 + int(math.log10(x))
while x >= 10:
sum = 0
for i in xrange(count):
sum += x % 10
x /= 10
x = sum
At the end, x will be a single-digit number as described, and count is the number of original digits.
I would like to give credit to this stackoverflow question for a succinct way to sum up digits of a number, and the answers above for giving you some insight to the solution.
Here is the code I wrote, with functions and all. Ideally you should be able to reuse functions, and here the function digit_sum(input_number) is being used over and over until the size of the return value (ie: length, if sum_of_digits is read as a string) is 1. Now you can use the while loop to keep checking till the size is what you want, and then abort.
def digit_sum(input_number):
return sum(int(digit) for digit in str(input_number))
input_number = input("Please enter a number: ")
sum_of_digits = digit_sum(input_number)
while(len(str(sum_of_digits)) > 1):
sum_of_digits = digit_sum(input_number)
output = 'Sum of digits of ' + str(input_number) + ' is ' + str(sum_of_digits)
print output
input_number = sum_of_digits
this is using recursive functions
def sumo(n):
sumof = 0
while n > 0:
r = n%10 #last digit
n = n/10 # quotient
sumof += r #add to sum
if sumof/10 == 0: # if no of digits in sum is only 1, then return
return sumof
elif sumof/10 > 0: #else call the function on the sumof
sumo(sumof)
Probably the first temptation would be to write
while x > 9:
x = sum(map(int, str(x)))
that literally means "until there is only one digit replace x by the sum of its digits".
From a performance point of view however one should note that computing the digits of a number is a complex operation because Python (and computers in general) store numbers in binary form and each digit in theory requires a modulo 10 operation to be extracted.
Thus if the input is not a string to begin with you can reduce the number of computations noting that if we're interested in the final sum (and not in the result of intermediate passes) it doesn't really matter the order in which the digits are summed, therefore one could compute the result directly, without converting the number to string first and at each "pass"
while x > 9:
x = x // 10 + x % 10
this costs, from a mathematical point of view, about the same of just converting a number to string.
Moreover instead of working out just one digit however one could also works in bigger chunks, still using maths and not doing the conversion to string, for example with
while x > 99999999:
x = x // 100000000 + x % 100000000
while x > 9999:
x = x // 10000 + x % 10000
while x > 99:
x = x // 100 + x % 100
while x > 9:
x = x // 10 + x % 10
The first loop works 8 digits at a time, the second 4 at a time, the third two and the last works one digit at a time. Also it could make sense to convert the intermediate levels to if instead of while because most often after processing n digits at a time the result will have n or less digits, leaving while loops only for first and last phases.
Note that however the computation at this point is so fast that Python general overhead becomes the most important part and thus not much more can be gained.
You could define a function to find the sum and keep updating the argument to be the most recent sum until you hit one digit.
def splitSum(num):
Sum = 0
for i in str(num):
m = int(i)
Sum = Sum + m
return str(Sum)
n = input("Please enter an integer: ")
count = 0
while count != 1:
Sum = splitSum(n)
count = len(Sum)
print(Sum)
print(count)
n = Sum

Categories