def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(n, n+1):
if n % i ==0:
nb.append(i)
sum1 = sum(nb) - nb[-1]
if sum1 > n:
return True
else:
return False
n = int(input("n:"))
print(richNumber(n))
I have 5 Test Cases:
n = 4
n = 12
n = 6
n = 20
n = 100
With n = 4 and 6 the output is false ,with n = 12,20,100 is supposed to be true but its showing false.
This function used to get all divisor of n in a list, if the sum of all divisor of n (not N) is larger than N is true, smaller is False
for i in (n, n+1)
Iterates over two numbers, n and n + 1, not all divisors. You need to use range to iterate from 1 to n
for i in range(1, n + 1)
Your current richNumber function will always return False because sum1 will
always be 0. Try the following code:
def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(1, n):
if n % i == 0:
nb.append(i)
sum1 = sum(nb)
if sum1 > n:
return True
else:
return False
Related
The question is: print out all numbers from 1 to 1000 that satisfy the two conditions:
Those are prime numbers
The numbers after being reversed are also prime numbers.
e.g., 13 satisfies (as 13 and 31 are prime numbers), but 19 does not satisfy (19 is a prime number, while 91 is not).
My codes:
def prime(n):
if n<2:
return False
for i in range(1, n):
if n%i == 0:
return False
else:
return True
def reverse(n):
List = []
while n>0:
List.append(n%10)
n = n//10
string = [str(integer) for integer in List]
a_string = "".join(string)
result = int(a_string)
print(result)
L = []
for i in range (1, 1000):
if prime(i) == prime(reverse(i)) == True:
L.append(i)
print(L)
Mine seems to contain some errors as the outcome is not as expected, either it shows none or still shows 19 in the list.
Thank you in advance!
First your prime method is wrong, because the loops starts at 1, and every numbre satisfies n%1 == 0 , it needs to starts at 2
def prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
Then your reverse method returns nothing so reverse(5) gives None, you have tried it manually.
def reverse(n):
values = []
while n > 0:
values.append(n % 10)
n = n // 10
return int("".join(map(str, values)))
Then simplify the condition to be
for i in range(1, 20):
if prime(i) and prime(reverse(i)):
L.append(i)
The reverse process can be done with string also, and so short that it can be inlined
L = []
for i in range(1, 20):
if prime(i) and prime(int(str(i)[::-1])):
L.append(i)
It would seem running prime twice is very inefficient. I would recommend the following:
def prime(n):
if n<2:
return False
for i in range(2, n):
if n%i == 0:
return False
return True
l = [i for i in range(1, 1001) if prime(i)]
print(*(x for x in l if int(str(x)[::-1]) in l))
I want to generate list of primes of the format x2+1 but I am not getting any output.
My code:
def LPrime(n):
for i in range(1,n):
x = i**2+1;
for j in range(2,x):
if x % j != 0:
print(x,i)
Please tell me what am I doing wrong.
The expected output should be something like
2,1
5,2
and so on
Also I am not able to execute it properly, I am using Ubuntu 22.04
There is no output when I try to
If if x % j == 0: you have a divisor. and j will not be 1 or x. So you should mark p as False (there is no prime). else, it is a prime; print it.
def LPrime(n):
for i in range(0, n):
x = i**2+1
p = True
for j in range(2, x):
if x % j == 0:
p = False
if p:
print(f"Prime = {x},\t i = {i}")
Don't forget to call it
>>> LPrime(4)
Prime = 1, i = 0
Prime = 2, i = 1
Prime = 5, i = 2
If you want n primes, use a while loop:
def LPrime(n):
count = 0
i = 0
while count < n:
x = i**2+1
p = True
for j in range(2, x):
if x % j == 0:
p = False
if p:
print(f"Prime = {x},\t i = {i}")
count += 1
i += 1
>>> LPrime(4)
Prime = 1, i = 0
Prime = 2, i = 1
Prime = 5, i = 2
Prime = 17, i = 4
Here's my code for printing the sum of prime divisors of each number between 18 to 25. But it is only printing 5.
For example:
18 has prime factors 2, 3 hence sum = 5,
19 is prime, hence sum of factors = 0,
20 has prime factors 2 and 5, hence sum = 7,
21 has prime factors 3 and 7, hence sum = 10,
22 has prime factors 2 and 11, hence sum = 13,
23 is prime. hence sum = 0,
24 has prime factors 2 and 3, hence sum = 5,
25 has prime factor 5, hence sum = 5
Therefore, it should print [5,0,7,10,13,0,5,5]
I believe I should use break statement but i tried it didn't work. As I am beginner in python, any kind of help much appreciated.
def isPrime(n):
i = 2
while i * i <= n:
# n has a factor, hence not a prime
if (n % i == 0):
return False
i += 1
# we reach here if n has no factors
# and hence n is a prime number
return True
def summ(l, r):
summ = 0
arrayofdivisors = []
arrayofsum = []
# iterate from lower to upper
for i in range(l, r + 1) :
# if i is prime, it has no factors
if (isPrime(i)) :
continue
for j in range(2, i):
# check if j is a prime factor of i
if (i % j == 0 and isPrime(j)) :
arrayofdivisors.append(j)
if(len(arrayofdivisors)>1):
ans = sum(arrayofdivisors)
arrayofsum.append(ans)
return arrayofsum
# Driver code
if __name__ == "__main__":
l = 18
r = 25
print(summ(l, r))
Try this
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def Sum(N):
SumOfPrimeDivisors = [0] * (N + 1)
for i in range(2, N + 1) :
if (SumOfPrimeDivisors[i] == 0) :
for j in range(i, N + 1, i) :
SumOfPrimeDivisors[j] += i
return SumOfPrimeDivisors[N]
arr=[]
for i in range(18,26):
if isPrime(i):
arr.append(0)
else:
arr.append(Sum(i))
print(arr)
It's almost impossible to tell because of the way you've formatted things, but the problem here is that your "return" statement is indented one position too far. Thus, you return at the end of the first loop, before it has a chance to check anything else. Un-indent the return arrayofsum and it should work.
Then, you are initializing arrayofdivisors outside the main loop, so it just kept getting larger and larger. Then, you weren't adding 0 to the list for prime numbers, as your spec required.
Note that if statements in Python do not need parentheses, like they do in C.
def isPrime(n):
i = 2
while i * i <= n:
# n has a factor, hence not a prime
if n % i == 0:
print(n,'not prime')
return False
i += 1
# we reach here if n has no factors
# and hence n is a prime number
print(n,"prime")
return True
def summ(l, r):
# iterate from lower to upper
arrayofsum = []
for i in range(l, r + 1) :
arrayofdivisors = []
# if i is prime, it has no factors
if isPrime(i):
arrayofsum.append(0)
continue
for j in range(2, i):
# check if j is a prime factor of i
if i % j == 0 and isPrime(j):
arrayofdivisors.append(j)
arrayofsum.append( sum(arrayofdivisors) )
return arrayofsum
# Driver code
if __name__ == "__main__":
l = 18
r = 25
print(summ(l, r))
def isPrime(n, i):
if i == n-1:
return ("True")
elif n%i == 0:
return ("False")
else:
return isPrime(n, i+1)
def sumOfPrime(m,n):
if m > 0 and n > 0 and m <= n:
if isPrime(m,2)==True:
temp = temp + m
return temp
else:
return (sumOfPrime(m+1,n))
else:
return temp
how can I fix the error "UnboundLocalError: local variable 'temp' referenced before assignment" without using a global variable
I reviewed your code, and this is my proposal:
def isPrime(n, i=None):
if i is None:
i = n - 1
while i >= 2:
if n % i == 0:
return False
else:
return isPrime(n, i-1)
else:
return True
def sumOfPrime(m, n):
sum = 0
for value in range(m, n+1):
if isPrime(value):
sum = sum + value
return sum
# --- test ---
result = sumOfPrime(1, 9)
print (result) # <-- prints 18
If the difference between m and n is quite high, then it is recommended that you use some type of sieve, to filter primes out in a given range. Otherwise, iterating over numbers from m to n and checking if the number is prime, it is going to be expensive for large m and n.
def is_prime(n):
if n <= 2:
return n > 1
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def prime_range_sum(m, n):
return sum(i for i in range(m, n + 1) if is_prime(i))
print(prime_range_sum(1, 9))
# prints 17
Here's my version, which I kept as close as possible to the original, while fixing some errors and making some adjustments.
def isPrime(n, i=2): # since you always use 2, just make it default
if i == n-1:
return True # return a boolean True instead of a string
elif n%i == 0:
return False # return a boolean False instead of a string
else:
return isPrime(n, i+1)
def sumOfPrime(m,n,total=0): # we will need to carry the total around, make default to 0
if 0 < m <= n: # we can simplify this complex condition
if isPrime(m):
total += m # if it's prime, increase the total...
return sumOfPrime(m+1, n, total) # and pass it to the next recursion
return total # if this is the last recursion, return total
# Example run
total = sumOfPrime(10,45)
print(total) # prints 264
def prime_factors(n):
i = 2
lst = []
while i <= n:
if isprime(i):
lst.append(i)
i += 1
return lst
def isprime(n):
n = isdivisor(n)
i = 2
lst = []
for j in n:
while i <= j/2:
if j % i != 0:
return True
else:
return False
i += 1
def isdivisor(n):
i = 2
lst = []
while i <= n/2:
if n % i == 0:
lst.append(i)
i += 1
return lst
print prime_factors(15)
First, I tried to find divisors of integer n and checked the divisors whether they are prime or not.However the output is somehow [10, 14, 15] instead of [3,5]. Is it because I can't do the assignment n = isdivisor(n) or something else ?
I just wrote a pice of code to do It, without using libs. I hope It can help you.
my code:
def get_square_root(n):
"""Return square root of n."""
return n ** (1.0 / 2)
def is_divisor(n, d):
"""Return True if n divides d, False otherwise."""
return n % d == 0
def is_prime(n):
"""Return True if n is prime, False otherwise."""
limit = int(get_square_root(n))
for i in range(2, limit+1):
if is_divisor(n, i):
return False
return True
def get_prime_factors(n):
"""Return a list of the prime factors of n."""
prime_factors = []
for i in range(2, n):
if is_divisor(n, i) and is_prime(i):
prime_factors.append(i)
return prime_factors
if __name__ == '__main__':
n = 15 # Change n to test
prime_factors = get_prime_factors(n)
print(prime_factors)
output:
[3, 5]
There are some logical errors in your code. You are overcomplicating things somewhat by returning lists of divisors and primes. You already have a loop in the prime_factors() to go through all the numbers from 2 to n. So you can simplify your isdivisor() and isprime() functions:
def isdivisor(i, n):
return n % i == 0
def isprime(n):
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
Then change your main loop in prime_factors() like this:
def prime_factors(n):
i = 2
lst = []
while i < n:
if isdivisor(i, n) and isprime(i):
lst.append(i)
i += 1
return lst
Output:
>>>prime_factors(15)
[3,5]