Find all the divisors of a number using Python [duplicate] - python

This question already has answers here:
What is the best way to get all the divisors of a number?
(18 answers)
Closed 2 years ago.
I am trying to write a Python script that will find prime numbers. In the way that I am going about this, the script is going to take a number from a range, determine the factors, determine if the only two factors are 1 and itself, and return true if it's a prime number. I need help with my code to find the factors.
num = int(input("enter: "))
i = 1
while i < num:
if num % i == 0:
print(i)
i += 1
else:
pass
The i is set to 1 because you can't divide by 0. However, the return starts to work, however, it only returns a couple of numbers, not the full list that I am hoping for. For example, you input 20, it returns only 1 and 2.

You're only incrementing i in the "is even" case. This'd fix it:
num = int(input("enter: "))
i = 1
while i < num:
if num % i == 0:
print(i)
i += 1
However, it's better to use range() for iterating over a range of numbers:
num = int(input("enter: "))
for i in range(1, num):
if num % i == 0:
print(i)

Related

Sum of digits in a number [duplicate]

This question already has answers here:
How to manage division of huge numbers in Python?
(4 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
This function is supposed to return the sum of all the digits in a number.
def sum_digits(num):
if int(num) <= 0:
return 0
else:
sum = 0
while int(num) != 0:
n = int(num) % 10
num = int(num) / 10
sum = int(sum + n)
return sum
It works fine for smaller numbers, but if i enter for example number 999999999999999999999999999999999 it returns 74 instead of 297.
Thanks for help
You need to divide with (//) instead of (/), because that would return a floating number.
You need to do something like this:
def sum_digits(num):
num = int(num)
if num <= 0:
return 0
else:
sum = 0
while num != 0:
n = num % 10
num //= 10
sum += n
return sum
(I reformated your code a little for better readability.)
edit: typo fixed
I approached your problem a little different
number = 999999999999999999999999999999999
number = str(number)
sum = 0
for digit in number:
digit = int(digit)
sum = digit+sum
print(sum)

Finding magic numbers in python [duplicate]

This question already has answers here:
Sum the digits of a number
(11 answers)
Closed 2 years ago.
I am trying to find the magic number in this program but I got stuck on this part and am not sure where to go next. I have searched up many ways on the internet but they are all using more complex code that I have not learned yet.
Example
input 45637
4+5+6+3+7 = 25
2+5 = 7
7 = magic number
num = int(input("Enter a positive number : "))
ans = 0
while num > 0 or ans > 9:
digit = num % 10
num = num//10
print(digit)
Using statements and operators you have already learned as demonstrated in your code, you can use a nested while loop to aggregate the digits from the division remainders into a total as the number for the next iteration of the outer while loop:
num = 45637
while num > 9:
total = 0
while num > 0:
digit = num % 10
num = num // 10
total = total + digit
num = total
print(num)
This outputs:
7
One way:
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
Full code:
num = int(input("Enter a positive number : "))
ans = num
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
print(ans)
Output for input 45637:
7

Python: Find Prime Number Algorithm

Recently I was given a challenge to my coding skills by my teacher since he saw that I was already knowledgeable in what he was teaching. The question is as follows.
Create a program that prompts the user for 2 numbers. The program will then display all the prime numbers in between the two given numbers, including the given numbers. Note: You cannot assume the first input is bigger than the second input.
So I took this question and built a fairly simple algorithm and ran it and it worked. I opened it today to find out for some reason my output is occasionally wrong, for example when you input 8 and 29 I get 27. I am looking for HINTS as to what is wrong with my logic because I cannot for the life of me figure out what Im doing wrong. I dont want straight up fixes because I would like to learn as much from this and doing it as much as possible by myself.
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
numList = []
#Removing Even Numbers
for num in range(numbers[0],numbers[1] + 1):
if num % 2 != 0:
numList.append(num)
#Checking For Prime Numbers
for currNum in numList:
#Set Start number to divide
i = 2
while i < currNum:
#Checks if the currNum can be divisble by i and is a whole number
if currNum % i != 0:
i = i + 1
else :
numList.remove(currNum)
break
print(numList)
From what I have learned from testing this out it seems like 27 is never checked during my for loop or while loop even though it is in the numList array.
Never remove items form a list you are iterating over.
Instead create a new list:
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
primes = []
for num in range(numbers[0], numbers[1] + 1):
#Set Start number to divide
i = 2
while i < num:
#Checks if the currNum can be divisble by i and is a whole number
if num % i == 0:
break
i += 1
else:
primes.append(num)
print(primes)

Coding exclusions in a for loop (python) [duplicate]

This question already has answers here:
Sieve of Eratosthenes in Python
(3 answers)
Closed 6 years ago.
i'm trying to figure out how to exclude certain numbers (numbers that aren't prime) in my program. For example, I don't want 15 to be printed so I used the modulo to exclude numbers divisible by 5 but that eliminates 5, which is a prime number. Any help on how to code this would be huge help! Thank you...
start = int(input("Start number: "))
end = int(input("End number: "))
while start < 0 or end < 0:
print ("Start and end number must be positive. Try again.")
start = int(input("Start number: "))
end = int(input("End number: "))
while start > end:
print ("End number must be greater than start number. Try again.")
for x in range (start, end):
is_prime = True
for x in range (start, end):
trial = x % 2
trial1 = x % 5
trial2 = x % 3
if trial != 0 and trial1 != 0 and trial2 != 0:
print (x, "is a prime number")
x = x + 1
else:
is_prime = False
You can create a list of numbers you want to use in your loop let's call it loop_list and then simply use for x in loop_list, that avoid you setting up exclusions
If you want to be sure that N is a prime number, you have to check for all number to squareroot(N) if N%number != 0.
Are you looking for optimisation? If no, you just need that.
You can try this prime number logic :-
def check_prime(num):
notPrimeFlag = 'N'
for i in range(2, num):
if num % i == 0:
notPrimeFlag = 'Y'
break
if notPrimeFlag == 'N':
print("Prime number")

print factors of a number in python

I'm trying to print the factors of the number 20 in python so it goes:
20
10
5
4
2
1
I realize this is a pretty straightforward question, but I just had a question about some specifics in my attempt. If I say:
def factors(n):
i = n
while i < 0:
if n % i == 0:
print(i)
i-= 1
When I do this it only prints out 20. I figure there's something wrong when I assign i=n and then decremented i, is it also affecting n? How does that work?
Also I realize this could probably be done with a for loop but when I use a for loop I can only figure out how to print the factors backwards so that I get: 1, 2, 5, 10....
Also I need to do this using just iteration. Help?
Note: This isn't a homework question I'm trying to relearn python on my own since it's been a while so I feel pretty silly being stuck on this question :(
while i < 0:
This will be false right from the start, since i starts off positive, presumably. You want:
while i > 0:
In words, you want to "start i off at n, and decrement it while it is still greater than 0, testing for factors at each step".
>>> def factors(n):
... i = n
... while i > 0: # <--
... if n % i == 0:
... print(i)
... i-= 1
...
>>> factors(20)
20
10
5
4
2
1
The while condition should be i > 0 and not i < 0 because it will never satisfy it as i begins in 20 (or more in other cases)
Hope my answer helps!
#The "while True" program allows Python to reject any string or characters
while True:
try:
num = int(input("Enter a number and I'll test it for a prime value: "))
except ValueError:
print("Sorry, I didn't get that.")
continue
else:
break
#The factor of any number contains 1 so 1 is in the list by default.
fact = [1]
#since y is 0 and the next possible factor is 2, x will start from 2.
#num % x allows Python to see if the number is divisible by x
for y in range(num):
x = y + 2
if num % x is 0:
fact.append(x)
#Lastly you can choose to print the list
print("The factors of %s are %s" % (num, fact))

Categories