Beginner here. I tried to sum all divisors of a number but the number itself. I wrote a code without using elif.
def sum_divisors(n):
sum = 0
divisor = 1
while divisor < n:
if n == 0:
return 0
else:
n % divisor == 0
sum += divisor
divisor += 1
return sum
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
I got the answers 0, 1, 630 and 5151. Then, I rewrote the code by using elif. Got the right answers.
def sum_divisors(n):
sum = 0
divisor = 1
while divisor < n:
if n == 0:
return 0
elif n % divisor == 0:
sum += divisor
divisor += 1
else:
divisor += 1
return sum
print(sum_divisors(0))
print(sum_divisors(3))
print(sum_divisors(36))
print(sum_divisors(102))
There is something wrong in the first attempt, I feel it but I can't explain it. Is it related to the order of operations? Can someone explain what's going on in the execution of the first code?
You declared a statement with no usage n % divisor == 0 And in the second code block it is an elif statement. That's why the first code is not working - you have checked whether it is True but you did not add an elif statement and what should be executed there.
def sum_divisors(n):
sum1 = 0
divisor = 1
while divisor < n:
if n == 0:
return 0
elif n % divisor == 0:
sum1 += divisor
divisor += 1
else:
divisor += 1
return sum1
print(sum_divisors(36))
print(sum_divisors(102))
Related
def sum_divisors(n):
sum = 0
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
I attempted to find the range of the numbers with this that I found on another question asked on here but I'm honestly just completely stumped with this question that I'm being asked even with the help that's alread given within the question.
for i in xrange(1,n/2+1):
if n%i == 0:
I'm not sure how to properly input it so it ended up looking like this
def sum_divisors(n):
for i in xrange(1,n/2+1):
if n%i == 0:
sum = 0
return sum
# Return the sum of all divisors of n, not including n
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
This should work:
def sum_divisors(n):
sum = 0
for i in range(1, int(n/2 + 1)):
if (n % i) == 0:
sum = sum + i
return sum
Be careful: xrange is used in Python 2 while range is Python 3, more info at this other question.
def sum_divisors(n):
sum = 0
for i in range(n-1):
i +=1
if n%i == 0:
sum += i
return sum
this is quite simple and works
Use the sum() function to add a sequence.
And you only need to go up to the square root of the number, not half the number.
from math import sqrt
def sum_divisors(n):
if n < 1:
return 0
return sum(i for i in range(int(sqrt(n))+1) if n % i == 0)
I'm learning Python by doing Project Euler questions and am stuck on Problem #3.
I think I've found a solution that works, but when inserting the large number 600851475143 it just doesn't return anything. I believe that it just loads and loads cause even with 6008514 it takes 10 secs to return the answer.
# What is the largest prime factor of the number x?
import math
def isPrime(x):
try:
sqr = math.sqrt(x)
if x == 0 or x == 1:
return 0
for n in range (2 , int(sqr)+1):
if x % n == 0:
return 0
return 1
except:
return 'Give positive numbers.'
def largestPrimeFactor(x):
if isPrime(x) == 1:
return 'This number is prime.'
else:
largest = -1
mid = x/2
for n in range(2,int(mid)+1):
if isPrime(n):
if x % n == 0:
largest = n
if largest == -1:
return 'Enter numbers above 1.'
else:
return largest
print(largestPrimeFactor(600851475143))
This code should work:
import math
def isPrime(x):
try:
sqr = math.sqrt(x)
if x == 0 or x == 1:
return 0
n = 2
highest = x
while n < highest:
if x%n ==0:
return 0
highest = x/ n
n +=1
return 1
except:
return 'Give positive numbers.'
def largestPrimeFactor(x):
if isPrime(x) == 1:
return 'This number is prime.'
n = 2
highest = x
largest = 1
while n < highest:
if x%n == 0:
if isPrime(n):
largest = n
highest = x/n
n +=1
return largest
print(largestPrimeFactor(600851475143))
I made an optimization:
you check if every number is a factor of x while if for example 2 is not a factor of x for sure the maximum factor of x can be x/2. Hence if n is not a factor of x the maximum possible factor of x can just be x/n.
The code for large numbers just takes really long time, as pointed out by comments. I report other bugs.
Bug 1. Inappropriate use of try/except clause. It is recommended that try contains a single command and except catches the error. PEP8 also recommends specifying the type of error. Moreover, for your function, the error is never raised.
Bug 2. Redundancy. If x is not prime, you call isPrime for each value (let's call it i) from 2 to x/2. isPrime cycles for each number from 2 to sqrt(i). Therefore, isPrime(i) takes O(sqrt(i)) time, and we call it for i from 2 to x/2. Roughly, its running time is about O(x^(3/2)). Even if don't know a more optimal approach, this approach asks for memoization.
i have another way:
def Largest_Prime_Factor(n):
prime_factor = 1
i = 2
while i <= n / i:
if n % i == 0:
prime_factor = i
n /= i
else:
i += 1
if prime_factor < n:
prime_factor = n
return prime_factor
it faster than previous
try it:
import math
def maxPrimeFactors (n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
n = 600851475143
print(maxPrimeFactors(n))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am a beginner in Python and just starting to learn. Please help me with the below code.
def sum_divisors(n):
sum = 0
divisor = 1
while divisor < n
if n % divisor = 0
sum = sum + divisor
divisor += 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
However, I am getting the below error, please help:
Error on line 4:
while divisor < n
^
SyntaxError: invalid syntax
You missed the trailing ":": while divisor < n:.
There are also various problems with the indentation.
This may fix your code:
def sum_divisors(n):
sum = 0
divisor = 1
while divisor < n:
if n % divisor == 0:
sum = sum + divisor
divisor += 1
# Return the sum of all divisors of n, not including n
return sum
It's simple:
def sum_divisors(n):
sum = 0
divisor = 1
while divisor < n:
if n % divisor == 0:
sum = sum + divisor
divisor += 1
It's simple syntax: there's supposed to be a ":" after the while and if statements.
And indentation after that.
Also == for if statements
You need a colon (:) after the while and if statements and proper indentation, and the = is for variable assigning, the operator for equality is ==:
def sum_divisors(n):
sum = 0
divisor = 1
while divisor < n:
if n % divisor == 0:
sum = sum + divisor
divisor += 1
You need to put : after while,if,for and function definitions. Also you need to check the equality with == instead of =.
def sum_divisors(n):
sum = 0
divisor = 1
while divisor < n:
if n % divisor == 0:
sum = sum + divisor
divisor += 1
# Return the sum of all divisors of n, not including n
return sum
There were few mistakes of missing colon. I have fixed them.
def sum_divisors(n):
sum = 0
divisor = 1
while divisor < n:
if n % divisor == 0:
sum = sum + divisor
divisor += 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
Can someone help me and tell me why this doesn't work? The goal is to count the number of prime numbers that are produced by a given polynomial for inputs n in a specified range [a,b]:
def count_primes(poly, a, b):
primes = 0
if b >= a:
for n in range(a, b):
result = poly(n)
if result > 1:
for i in range(2, result):
if (result % i) == 0:
break
else:
primes += 1
else:
break
return primes
def poly(n):
return n**2 + n + 41
print(count_primes(poly, 0, 39))
The result should return 40 in this case.
[2] Problem Solution
Step-1. Take in the number to be checked and store it in a variable.
Step-2. Initialize the count variable to 0.
Step-3. Let the for loop range from 2 to half of the number (excluding 1 and the number itself).
Step-4. Then find the number of divisors using the if statement and increment the count variable each time.
Step-5. If the number of divisors is lesser than or equal to 0, the number is prime.
Step-6. Print the final result.
Step-7. Exit.
The problem is that the else clause in the nested loop refers to the if, when it should be activated only if the loop finished without break. Just change the identitation to:
if result > 1:
for i in range(2, result):
if (result % i) == 0:
break
else:
primes += 1
This is the wrong way to count primes:
if result > 1:
for i in range(2, result):
if (result % i) == 0:
break
else:
primes += 1
Should be:
if result > 1:
isPrime = True
for i in range(2, result):
if (result % i) == 0:
isPrime = False
break
if isPrime:
primes += 1
Also, it goes without saying. Easy optimizations for prime number detection. You only have to test for divisibility divisibility with 2 and all odd numbers between 3 and sqrt(result).
def count_primes(poly, a, b):
primes = 0
if b >= a:
for n in range(a, b+1):
result = poly(n)
if result > 1:
for i in range(2, result):
if (result % i) == 0:
break
else:
primes += 1
else:
break
return primes
def poly(n):
return n**2 + n + 41
print(count_primes(poly, 0, 39))
Problems:
you do primes += 1 too early. In your methods, you have to test until no possible division happens, then do the addition.
[a, b] The endpoints are both inclusive. Then you should use b+1 at your for n in range(a, b+1), which produces 40.
Question:
Given the prime number n, output the number of prime numbers
My code:
def kthPrime(self, n):
if n>10 and n%10 not in [1,3,7,9]:
return 0
if n == 2:
return 1
queue = []
num = 2
while num <= n:
if n%num == 0 and num != n:
return 0
if num>10 and num%10 not in [1,3,7,9]:
num += 1
continue
for i in range(2,num/2+1):
if num%i == 0:
num += 1
break
else:
queue.append(num)
num += 1
seq = queue.index(n) + 1
return seq
Error:
Your code ran too much time than we expected. Check your time complexity. Time limit exceeded usually caused by infinite loop if your time complexity is the best.
My Question: how to improve it
as user #Prune said , please read the guide first.
I'm not going to tell you how to improve your function , but I'm just gonna give you a faster way to see whether a number is prime or not and hopefully you will understand how to use the function that I'm gonna give you to improve your own function.
The source code :
class numChecker:
def is_prime(self,n):
if n == 2:
return True
if n % 2 == 0 or n < 2:
return False
self.square_root = int(n ** (1/2))
for divisor in range(3, self.square_root + 1, +2):
if n % divisor == 0:
return False
return True