Problem
Here is the problem I am trying to solve.
The prime factors of 13195 are 5, 7, 13, 29. What is the largest prime factor of the number 600851475143?
def prime_calc():
num = raw_input("What is the number you want the primes for?")
prim_num = []
x = 2
while num/x > 1:
new_num = num / x
if num % x == 0:
return prim_num.append(x)
elif num % x != 0:
new_num = num/x += 1
return prim_num.append(x)
else:
break
I keep getting an invalid syntax error starting from the bottom up to the fourth line that doesnt like my "+=" operator
This line:
new_num = num/x += 1
should be broken into two lines:
x += 1
new_num = num/x
The statement x += 1 in python doesn't return anything, so you can't use it as part of an expression.
Similarly, the two instances of:
return prim_num.append(x)
Also won't work, since the statement: prime_num.append(x) doesn't return anything.
You need to break this into:
prime_num.append(x)
return prime_num
num=int(input("Please enter number to calculate prime factor"))
k=0
item=[]
if(num%2==0):
prime=2
item.insert(k,prime)
k=k+1
j=3
flag=int(num/2)
while(j<flag and num>2):
if num%j==0:
prime=j
item.insert(k,prime)
k=k+1
num=num/j
j=j+2
else:
j=j+2
if k==0:
print("sorry no prime factor for this number")
else:
print("Please find the largest prime factor below")
print(item.pop())
Related
I have to count the sum of all prime numbers that are less than 1000 and do not contain the digit 3.
My code:
def primes_sum(lower, upper):
total = 0
for num in range(lower, upper + 1):
if not num % 3 and num % 10:
continue
elif num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
total += num
return total
total_value = primes_sum(0, 1000)
print(total_value)
But still I don't have right result
def primes_sum(lower, upper):
"""Assume upper>=lower>2"""
primes = [2]
answer = 2
for num in range(lower, upper+1):
if any(num%p==0 for p in primes): continue # not a prime
primes.append(num)
if '3' in str(num): continue
answer += num
return answer
The issue in your code was that you were checking for num%3, which checks whether num is divisible by 3, not whether it contains a 3.
I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.
My objective of the below code is
check if entered number is a prime
if not print the next biggest prime
def primetest (num):
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting any output.
Time comlexity of your code is O(N) when it find a number which is prime or not.
There is no pointing on dividing from 2 to len(num)-1. It is enough to loop from 2 to sqrt of the given number. Therefore time complexity reduce to O(n) to O(log(n)).
import math
num = int (input ("enter a number:"))
def primeTest(num):
isPrime = 0
for i in range(2,int(math.sqrt(num)+1)):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print(num, "is a prime number")
else:
num = num + 1
repeatTest(num)
def repeatTest (num):
isPrime = 0
for i in range(2,int(math.sqrt(num))):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print("Next Prime: ", num)
else:
num = num + 1
repeatTest(num)
primeTest(num)
The logic which you are using to find if a number if prime seems wrong .
Taking a integer like 9 prints "9 is a prime number" .
And also you are checking for next prime numbers from 2 to Num .
Num being the input , you cant get a number greater than that .
It exits from the loop without even getting in , therefore not printing anything when you are searching for next prime .
You need to change the logic .
write a separate function for checking prime and end the loop when you find the next prime number instead of stopping at num .
I'm trying to write a program in python that can either print 1 through nth numbers of the prime number sequence, or print just the nth number of the prime number sequence. Here is the code.
import math
P = 2
X = raw_input('Choose a number: ')
Y = 1
def prime(P, Y):
Choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
if Choice == "1":
while Y <= int(X):
isprime = True
for x in range(2, int(P) - 1):
if P % x == 0:
isprime = False
break
if isprime:
print P
Y += 1
P += 1
elif Choice == "2":
prime(P, Y)
Basically, i have the first part down, so that it prints 1 through nth numbers of the prime sequence. However, I'm quite lost on how to make it calculate just the nth prime, where the nth prime is the given through raw input. It must be possible to do this in python, however, how would it be done, and what would be the best way to do so, without having to add too many new variables that i don't have here, (though i would be fine doing so). Help would be appreciated.
Add a condition so that if either the user wants to print all numbers, or you have reached the final prime number of the sequence, the number will be printed. (I have also replaced some of the variable names with more descriptive ones, and altered it so that the function is passed the number_of_primes as its only parameter, which would seem to make more sense.)
def print_primes(X):
choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
count = 1
n = 2
while count <= X:
is_prime = True
for i in range(2, int(n) - 1):
if n % i == 0:
is_prime = False
break
if is_prime:
if choice == "1" or count == X:
print n
count += 1
n += 1
number_of_primes = int(raw_input('Choose a number: '))
print_primes(number_of_primes)
Just only print if it's the Yth number:
if isprime:
Y += 1
if Y == X:
print P
I wrote a code in python to find the nth prime number.
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
while mod < (num - 1):
ptrue = 'true'
if num%(num-mod) == 0:
ptrue = 'false'
break
mod += 1
if ptrue == 'true':
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print(prime(nth)
The code looked fine to me, but it returns an error when I run it:
Traceback (most recent call last):
File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>
print(prime(nth))
File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime
if ptrue == 'true':
UnboundLocalError: local variable 'ptrue' referenced before assignment
It appears to me as if it is trying to say that I am referring to ptrue in the last line even though I am not. What is the problem here... Can anyone help?
how about using Boolean ? and initalize ptrue out of while loop
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
ptrue = True
while mod < (num - 1):
if num%(num-mod) == 0:
ptrue = False
break
mod += 1
if ptrue == True:
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print prime(nth)
ptrue is local to your while loop which goes out of scope as soon as the while loop ends. so declare ptrue before the start of your inner while loop
Get rid of ptrue entirely and use else with your inner loop. For example:
while mod < (num - 1):
if num % (num - mod) == 0:
break
mod += 1
else:
primes += 1 # only executes if loop terminates normally, without `break`
You can try this:
#This program finds nth prime number
import math
def is_prime(number):
if number < 2:
return False
if number % 2 == 0:
return False
else:
for i in range(3, number):
if not number % i:
return False
return True
n = input('Enter n: ')
#This array stores all the prime numbers found till n
primes = []
for i in range(100000):
if is_prime(i):
primes.append(i)
if len(primes) == n:
break
print("nth prime number is: " + str(primes[n-1]))
The first part is define a function that calculates the next prime number given any number.
import math
def is_prime(x): # function
for i in range(2,int(math.sqrt(x))+1):
if x%i == 0:
return is_prime(x+1)
return x
For example, is_prime(10) will return 11.
The next step is to write a generator that returns a list of prime numbers.
def get_prime(k): # generator
cnt = 1
n = 2
while cnt <= k:
yield(is_prime(n))
n = is_prime(n) + 1
cnt += 1
For example, get_prime(5) will return [2,3,5,7,11].
The code below can help you test the results.
a = get_prime(50)
lists = list(a)[:]
for idx, value in enumerate(lists):
print("The {idx}th value of prime is {value}.".format(idx = idx+1, value = value))
All answers depends on user input, but here is a simple code to give nth number, no matter how big the n is ....
def isprime(n): # First the primality test
if n<2:
return False
for i in range(2,n):
if n%i==0:
return False
break
else:
return True
def nthprime(n): # then generic code for nth prime number
x=[]
j=2
while len(x)<n:
if (isprime(j)) == True:
x.append(j)
j =j+1
print(x[n-1])
n=int(input('enter n'))
a=[2,3,5,7]
i=3
j=9
while i<n:
flag=0
j=j+2
for k in range(len(a)):
if (a[k]<=int(j**0.5) and j%a[k]==0):
flag=1
break
if flag==0:
a=a+[j]
i=i+1
print(a[n-1])
Try this.
n = int(input())
count=1
u=2
prime=[]
while(count<=n):
temp=0
for i in range(2,u):
if(u%i==0):
temp=1
if(temp==0):
count+=1
prime.append(u)
u+=1
print(prime[-1])
Program to find nth Prime Number.
def nth_Prime(num):
Semi = num*num
Res_1 = [True for i in range(Semi+1)]
prime = 2
while prime*prime <= Semi:
if Res_1[prime] == True:
for i in range(prime*prime, Semi+1, prime):
Res_1[i] = False
prime += 1
Res_2 = []
for i in range(2, Semi+1):
if Res_1[i]:
Res_2.append(i)
return Res_2[num-1]
if __name__ == "__main__":
num = int(input("Enter nth Number: "))
print(nth_Prime(num))
Try this out ,I just made few changes in yours.
Here I am checking for each prime number using all(num%i!=0 for i in range(2,num)) checking its remainder not equal to zero so if it is true for that range (starting from 2 and less than itself) it is a prime and for that all() function helps me later if its a prime I increment the 'p' count and check till 'p' is less than the 'n'(Input Number) so when it equates the condition its the nth prime we are looking for.
n=raw_input("enter the nth prime ")
num=4
p=2
while p <int(n):
if all(num%i!=0 for i in range(2,num)):
p=p+1
num=num+1
print "nTH prime number: ",num-1