Print prime numbers in a range of given numbers - python-3.x

I'm trying to print all primes into a range of given numbers (low and max, given numbers included).
For example:
num1=10, num2=20
>>> 11, 13, 17, 19
My code fails in some occasions and I can't understand why:
num1 = int(input('First number is: '))
num2 = int(input('Second number is: '))
if num2 <= num1:
num1,num2 = num2,num1
for i in range(num1, num2+1):
for p in range(2,int(num2**0.5)+1):
if i%p == 0:
break
else:
print(i,' ',end = '')
print('\n')
Results:
1 to 7 >>> 1 3 5 7 (omits 2)
1 to 30 >>> 1 7 11 13 17 19 23 29 (omits 2,3,5)
1 to 60 >>> 1 7 11 13 17 19 23 29 (omits 2,3,5,7)
0 to 0 >>> 0 (prints 0 -> not a prime number)
0 to 7 >>> 1 3 5 7 (omits 2)
How can I correct this? Thanks a bunch!
ps. number 1 is not a prime too.

The mistake in your code was not having an i in the second part of the inner for loop range as opposed to num2
num1 = int(input('First number is: '))
num2 = int(input('Second number is: '))
if num2 > num1:
num1, num2 = num2, num1
for i in range(num1, num2+1):
if i == 0 or i == 1: continue
for p in range(2,int(i**0.5)+1): # the second part should be int(i**0.5) + 1, not int(num2**0.5)+1
if i%p == 0:
break
else:
print(i,' ',end = '')
Also rather than having two branches for num1 < num2 and the other way around, you can do something like below. Further in terms of code design, it would be better to decompose this slightly into an is_prime method. That way, if you ever want to write a quicker primality tester, you could easily edit the helper function as opposed to messing with the main code.
def is_prime(num):
if i == 1: return False
for p in range(2,int(num**0.5)+1):
if num % p == 0:
return False
return True
inp1 = int(input('First number is: '))
inp2 = int(input('Second number is: '))
num1 = min(inp1, inp2)
num2 = max(inp1, inp2)
for i in range(num1, num2+1):
if is_prime(i):
print(i,' ',end = '')
print('\n')

You didn't consider the division of the number by the number itself into consideration.
i.e. When range was 1 to 30, sqrt(30)+1 = 5+1 = 6, all nos below six had a case where they were divided by the number itself as 2%2,3%3 ... i%i.
Workaround would be to change the range of inner for loop as :
for i in range(num1, num2+1):
for p in range(2,int(i**0.5)+1): #Change num2 to i to avoid i%i
if i%p == 0:
break
else:
print(i,' ',end = '')
It is better to abstract the code like the one done by gowrath to avoid mistakes.

Related

FIND THE PERFECT NUMBER IN PYTHON

I do have an answer already but I'm curious if there's a better method on coding this problem through python. Thank you.
A number is called a perfect number if it is equal to the sum of all of its divisors, not including
the number itself. For instance, 6 is a perfect number because the divisors of 6 are 1, 2, 3, 6
and 6 = 1 + 2 + 3. As another example, 28 is a perfect number because its divisors are 1, 2, 4,
7, 14, 28 and 28 = 1 + 2 + 4 + 7 + 14. However, 15 is not a perfect number because its divisors
are 1, 3, 5, 15 and 15 6= 1 + 3 + 5. Write a program that finds all four of the perfect numbers
that are less than 10000.
Here is my answer.
for i in range(1,10000):
summ = 0
for m in range(i):
if i % (m+1) == 0:
summ = summ + (m+1)
g = summ - i
if g == i :
print(g)
Here is perfect number algorithm that checks for perfect numbers using the Lucas Lehmer Test:
def ffs(x):
return (x&-x).bit_length()-1
def levelx(N, withstats=False):
if N <= 1: return False
temp = N
newlevel = temp.bit_length()
primetest = temp//(2**(ffs(temp)))
offset = temp//primetest
s = 4
nextlevel = newlevel // 2
check = temp // (2**nextlevel)
prevtemp = 2**nextlevel
if withstats == True:
print (newlevel, newlevel, temp)
print (newlevel, nextlevel+one, prevtemp)
if (prevtemp & (prevtemp-1) == 0) and prevtemp != 0:
if offset.bit_length() == primetest.bit_length():
if ((primetest+1) & ((primetest+1)-1) == 0):
for x in range(primetest.bit_length()-1):
s = (s * s - 2) % primetest
if withstats == True:
print(s)
if s in [0,2]: return True
return False
else: return False
else: return False
else: return False
Here is the output:
In [645]: for x in range(2,100):
...: if levelx((2**(x-1))*(2**x-1)) == True:
...: print(x, (2**(x-1))*(2**x-1))
...:
...:
2 6
3 28
5 496
7 8128
13 33550336
17 8589869056
19 137438691328
31 2305843008139952128
61 2658455991569831744654692615953842176
89 191561942608236107294793378084303638130997321548169216
You can use gmpy2 to speed these up by about 10x.
for j in range(1,10000):
sum=0
for I in range(1,J):
if J%I==0:
sum= sum + I
if j==sum:
print(J," is a perfect square")

How to find number in list which has the biggest number of prime?

I want to write a program that receives 10 entries and at the end it should print the number that has the greatest number of prime factors along with the number of its prime factors in the output. And, if some of the inputs have the same condition, the program will print the biggest one.
The code that I wrote executed all conditions except the final condition.
How should I write a code for a case where two numbers have the same numbers of prime factors (when I want the bigger number to be my output)?
For example both 678 and 84 have 3 prime factors . The output of my code is 84, while I want the output to be 678 (the bigger number).
input:
123
43
54
12
76
84
98
678
543
231
Correct output:
678 3
but my output:
84 3
a = [0,0,0,0,0,0,0,0,0,0]
#a = [123,43,54,12,76,84,98,678,543,231]
b = [0,0,0,0,0,0,0,0,0,0]
def is_first (number):
Prime_number= 0
for m in range(1, (number //2)+1, 1):
if number % m == 0:
Prime_number += 1
if Prime_number > 1:
is_prime = 0
else:
is_prime = 1
return is_prime
for i in range(0,10,1):
a[i] = input()
for j in a:
numbers= 0
for k in range(2, int(j)//2, 1):
if int(j) % k == 0:
if is_first (k) == 1:
numbers += 1
b[a.index(j)] = numbers
index_of_same = [i for i, e in enumerate(b) if e == max(b)]
n = []
for t in index_of_same:
n.append(a[t])
print(str(max(n))+ ' ' + str(max(b)))
When you append the numbers that have the highest number of prime factors to the list n, you are storing them as strings and not integers. Hence when you do the max() function on n, which holds 84,678 and 231, 84 is returned. I would suggest you to convert the numbers using int(), when storing into n and then perform the max()function on it. Just tweak your code as under:
for t in index_of_same:
n.append(int(a[t]))
Your code is cumbersome IMO, so I'd like to suggest a simpler version:
def getNumOfFactors(n):
num = 0
factor = 1
while n > 1:
factor += 1
if n % factor == 0:
num += 1
n /= factor
while n % factor == 0:
n /= factor
return num
def getMaxValue(values):
factors = [getNumOfFactors(n) for n in values]
tuples = zip(factors,values)
sorted_tuples = sorted([tuple for tuple in tuples],key=lambda x: x[0])
max_tuples = [tuple for tuple in sorted_tuples if tuple[0] == sorted_tuples[-1][0]]
sorted_max_tuples = sorted([tuple for tuple in max_tuples],key=lambda x: x[1])
return sorted_max_tuples[-1]
maxValue = getMaxValue([123,43,54,12,76,84,98,678,543,231])
print(maxValue)

24 game using Python3

24 is a mental arithmetic game, first played using poker cards. Given four integers, the objective is to produce the number 24 using the standard arithmetic operators +, −, ∗ and /, while consuming all four numbers in the process.
For example, given the numbers { 2, 3, 5, 6 }, one could do . . .
2 * 3 = 6 , 5 * 6 = 30 , 30 - 6 = 24 and so on
Note: The given numbers can be used in any order to produce 24.
Write a program that takes in four integers, and determines whether it is possible to reach 24 from those numbers. You can assume the number 0 will not form part of the input.
I am not sure how to let the function run my 4 inputs
import itertools
ints = input('Enter 4 integers: ').split()
n1=int(ints[0])
n2=int(ints[1])
n3=int(ints[2])
n4=int(ints[4])
def with_brackets(lst, ops_lst):
for op in ops_lst: #calculate when no brackets
expr1 = '('+lst[0]+op[0]+lst[1]+')'+op[1]+lst[2]+op[2]+lst[3]
expr2 = '('+lst[0]+op[0]+lst[1]+op[1]+lst[2]+')'+op[2]+lst[3]
expr3 = lst[0]+op[0]+'('+lst[1]+op[1]+lst[2]+')'+op[2]+lst[3]
expr4 = '('+lst[0]+op[0]+lst[1]+')'+op[1]+'('+lst[2]+op[2]+lst[3]+')'
for expr in [expr1, expr2, expr3, expr4]:
try:
t=eval(expr)
except: #except zerodivision error
pass
if abs(t-24) < 0.001:
return expr
return 0
#return 4 numbers to calculate 24
def hasMethod(numbers, ops_lst):
for lst in itertools.permutations(numbers):
lst = list(map(lambda x:str(x), lst))
#without brackets
for op in ops_lst:
expr = lst[0]+op[0]+lst[1]+op[1]+lst[2]+op[2]+lst[3]
if abs(eval(expr)-24) < 0.001:
return expr
#with brackets
expr = with_brackets(lst, ops_lst)
if expr != 0:
return expr
return 0
#method of return 4 numbers to calculate 24,no way return"No Method"
def cal_24(numbers):
ops = ['+','-','*','/']
ops_lst = [[i,j,k] for i in ops for j in ops for k in ops]
expr = hasMethod(numbers, ops_lst)
if expr != 0:
return expr
else:
return 'No method!'
#ways to calculate 24 at all situaions
def main():
numbers_lst = [[i,j,k,l] for i in range(1,14) for j in range(1,14)\
for k in range(1,14) for l in range(1,14)]
for numbers in numbers_lst:
a = list(map(lambda x: str(x), numbers))
methodInfo = "[%s,%s,%s,%s]: %s\n"%(a[0],a[1],a[2],a[3],cal_24(numbers))
print(methodInfo)
main()
Expected results:
Example 1:
Enter 4 integers: 2 3 5 6
Yes! 24 is reachable from { 2, 3, 5, 6 }
Example 2:
Enter 4 integers: 1 1 1 1
Noooo :( 24 is unreachable from { 1, 1, 1, 1 }
Example 3:
Enter 4 integers: hello
Input must consist of 4 integers
This question is very interesting.
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()

My code for finding Prime Number is working fine but printing an unexpected value of 9. Explain how?

I have written a logic to find Prime Number up to some entered value. It is working fine but printing an unexpected 9 which don't go well with logic as 9%3 will be 0 and it have to skip that number.
n = int(input())
for i in range(2,n+1):
for j in range(2,n+1):
if i%j == 0 and i!=j:
break
else:
print(i,end=" ")
break
Input : 20
Output : 2 3 5 7 9 11 13 15 17 19
You output a candidate number as soon as it is found not divisible by any other number, so for the candidate number 9, as soon as the inner loop starts with the divisor number 2, it would immediately go into the else block and output the number and break the inner loop because 9 is not divisble by 2.
You should wait until all the divisors from the inner loop have exhausted before deciding that the candidate number from the outer loop is indeed a prime number, and for that you can use the for-else construct:
n = int(input())
for i in range(2, n + 1):
for j in range(2, n + 1):
if i % j == 0 and i != j:
break
else:
print(i, end=" ")
Sample input/output:
20
2 3 5 7 11 13 17 19
Just take a variable, e.g. is_prime to set it to True/False by checking if the number gets divided by any number in closed interval [2, n/2].
Do not decide immediately and come out of the loop once the if expression gets satisfied using break as you are doing.
With a tiny change in your code, you may make your code working and with less number of iterations (to decrease runtime complexity) as follows.
n = int(input())
for i in range(2,n+1):
is_prime = True
for j in range(2, n//2 + 1):
if i % j == 0 and i != j:
is_prime = False
break
if is_prime:
print(i, end= " ")

Finding largest prime factor too slow in Python

Question:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
And I tried to solve it by using the below snippet, its taking long time to run. Is there any best way to solve this problem?
def find_prime(num, ranger):
count = 0
prime = True
for i in range(2, num):
if num % i == 0:
count = count + 1
if count > 1:
prime = False
return prime
return prime
prime_list = []
target = 600851475143
for i in range(2,target ):
if target % i == 0:
print(i)
if find_prime(i,target) and i % 2 == 0:
prime_list.append(i)
print(prime_list)
print(max(prime_list))
Please suggest.
n=600851475143
d=2
while d < n/d:
if n%d==0:
n/=d
else:
d+=1
print n

Resources