I'm not sure if this is the right place to ask but I have run into a wall, code-wise. I am trying to find the 9th Fibonacci number which is a Prime number but am having problems. First, my function to check if the number is Prime returns None for single digit prime numbers (2,3,5,7). Next, I think the value I'm looking for is 514229 as shown here but my program shows gives me the value 17711 as the 9th Fibonacci prime which is incorrect. My code is posted below:
def isPrime(n):
n = abs(int(n))
if n < 2:
return False
elif n == 2:
return True
elif not n & 1:
return False
else:
for x in range(3, n/2):
if n % x == 0:
return False
return True
def chkFibonacci():
num1 = 1
num2 = 1
mySum = 0
ctr = 0
choice = 'n'
while (choice != 'y'):
mySum = num1+num2
#print mySum
if (isPrime(mySum)== True):
ctr = ctr + 1
print mySum
if (ctr == 9):
print mySum
break
num1 = num2
num2 = mySum
chkFibonacci()
print isPrime(3)
Any help is appreciated. Thanks in advance!!
return True in the else branch of isPrime seems to be indented too much.
Related
The sum of digit is running well, but Why is the factorial section not working? Is there any mistakes that I made with the if else, or the break ?
NUM = int (input ("Enter a number "))
if NUM > 1:
for x in range (2, NUM):
if (NUM % x) == 0:
temp = NUM
sod = 0
while temp > 0:
remainder = temp % 10
sod += remainder
temp = temp//10
print (sod)
break
else:
factorial = 1
for I in range (1, NUM + 1,1):
factorial *= I
print (factorial)
else:
temp = NUM
sod = 0
while temp > 0:
remainder = temp % 10
sod += remainder
temp = temp//10
print (sod)
Your break statement on line 12 is outside the if statement, so the for loop will break after the first pass regardless of the value of NUM. Are you sure you didn't mean to indent the break another four spaces?
# example of factorial with prime numbers
num = int(input("Enter a number"))
factorial = 1
if num%2 == 0:
for i in range(1, num + 1):
factorial = factorial*i
print("The factorial of ",num," is",factorial)
Below code checks if the number is prime or odd number. if its prime it finds the factorial of that number and if its odd number then it sums the range of the number. Hope its what you were looking for.
NUM = int(input("Enter number here"))
if NUM > 0:
if NUM % 2 == 0:
factorial = 1
for i in range(1, NUM +1):
factorial = factorial*i
print(factorial)
else:
sum_of_NUM = 0
for x in range(NUM+1):
sum_of_NUM += x
print(sum_of_NUM)
else:
print("something you want to put")
I have a function that takes a number (for example, 5) and returns the first prime number after the input number (in this case, it would be 7).
This is my code:
def prime(n):
np=[]
isprime=[]
for i in range (n+1,n+200):
np.append(i)
for x in range(2,199):
for j in np:
if x%j!=0:
isprime.append(x)
return min(isprime)
However, this code doesn't work (it always returns 2). Where is the mistake?
You have a few mistakes, most notably np is clearly meant to be the potential primes (it starts at n+1 which is the first potential number that fits your critera "the first prime number after the input number"), and yet you add x to your prime list, which is from range(2,199), you should be using:
isprime.append(j)
Your primality test is also the wrong way round as a result, you should be using:
j % x != 0
Lastly, you can't append a number if that condition is true in one case, it has to be true in all cases (where x is an integer which satisfies 2 <= x < j), because of this you should switch your second set of for loops around (the x loop should be the inner loop), and you should also only loop up to j-1 (the number being tested). Additionally, you should instead choose to not add an item if j % x == 0:
for ...:
val_is_prime = True
for ...:
if j % x == 0:
val_is_prime = False
break
if val_is_prime:
isprime.append(j)
This results in the following code:
def prime(n):
np=[]
isprime=[]
for i in range (n+1,n+200):
np.append(i)
for j in np:
val_is_prime = True
for x in range(2,j-1):
if j % x == 0:
val_is_prime = False
break
if val_is_prime:
isprime.append(j)
return min(isprime)
And test run:
>>> prime(5)
7
>>> prime(13)
17
>>> prime(23)
29
Note that there's several other efficiency improvements that could be made, but this answer focuses on the mistakes rather than improvements
Try this one, the most pythonic and clear way to do this that I found (but probably not the most efficient):
def is_prime(x):
return all(x % i for i in range(2, x))
def next_prime(x):
return min([a for a in range(x+1, 2*x) if is_prime(a)])
print(next_prime(9))
https://www.geeksforgeeks.org/python-simpy-nextprime-method/
from sympy import *
# calling nextprime function on differnet numbers
nextprime(7)
nextprime(13)
nextprime(2)
Output:
11 17 3
This code working.
def prime(n):
next_prime = n + 1
prime = True
while True:
for i in range(2, next_prime):
if next_prime%i ==0:
prime = False
break
if prime:
return next_prime
else:
next_prime = next_prime + 1
if next_prime % 2 == 0:
next_prime = next_prime + 1
prime = True
if __name__=="__main__":
print(prime(5))
Here is one working sample.
inputNumber = int(input("Enter number to find next prime: "))
def nextPrime(inputNum):
for nextNumToChk in range(inputNum+1, inputNum +200):
if nextNumToChk > 1:
# If num is divisible by any number between 2 and val, it is not prime
for i in range(2, nextNumToChk):
if (nextNumToChk % i) == 0:
break
else:
#found the prime
return nextNumToChk
result = nextPrime(inputNumber)
print "Next Prime is : ",result
Output:-
Enter number to find next prime: 5
Next Prime is : 7
def is_prime(n):
# Corner case
if n <= 1:
return False
# Check from 2 to n-1
for i in range(2, n):
if n % i == 0:
return False
return True
def first_prime_over(n):
prime_number = (i for i in range(n) if is_prime(i))
try:
for i in range(0,n):
(next(prime_number))
except StopIteration:
prime_number_next = (i for i in range(n,n+1000) if is_prime(i))
print(next(prime_number_next))
first_prime_over(10)
Try this one:
def find_next_prime(n):
return find_prime_in_range(n, 2*n)
def find_prime_in_range(a, b):
for c in range(a, b):
for i in range(2, c):
if c % i == 0:
break
else:
return c
return None
def main():
n = int(input('Find the next prime number from: '))
print(find_next_prime(n+1))
if __name__ == '__main__':
main()
n = int(input("Enter a number"))
while True:
n+=1
for x in range(2,n):
if n%x==0:
break
else:
print("next prime number is",n)
break
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
This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results.
I tried to change it to say if num >= 1: and for i in range(1,num), but then when I ran it, the only result was 1 is a prime number!. Thanks!
for num in range(1,1001):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,"is a prime number!")
You should not write for i in range(1, num):, because (any number) % 1 == 0. if num >= 1: can also be removed, because it's always true.
Try the following code:
for num in range(1, 1001):
for i in range(2, num):
if num % i == 0:
break
else:
print num, 'is a prime number'
And remember, technically speaking, 1 isn't a prime number.
Leave your code as is and above the main for loop add:
print("1 is a prime number")
a = int(input("enter the start number"))
b = int(input("enter the end number"))
for i in range(a,b+1):
if i > 1:
for j in range(2,i):
if i % j == 0:
break
else:
print(i,"is a prime number")
import math
n1 = 1000
run_lim = math.ceil(math.sqrt(n1))
prm_num = [2]
for i in range (1,n1+1) :
if i == 1 :
continue
else :
count = 0
for j in range (len(prm_num)) :
if (prm_num[j] <= run_lim) and (i%prm_num[j]) == 0 :
count += 1
if count == 0 :
prm_num.append(i)
print("The Prime Numbers are :- \n")
print(*prm_num, sep=",")
import gmpy2
c = []
for i in range(1,1000):
if gmpy2.is_prime(i)==True:
c.append(i)
print(c)
prime = [2]
while len(prime) <= 1000:
i=3
a = 0
for number in prime:
testlist= []
testlist.append(i%number)
if 0 in testlist:
i=i+1
else:
prime.append(i)
i=i+1
print(prime[999])
Trying to make a program that computes primes for online course. This program never ends, but I can't see an infinite loop in my code.
A prime number is a number that can only be divided by exclusively one and itself.
My logic is that if a number can be divided by prime numbers preceding it then it is not prime.
As the comments to your question pointed out, there is several errors in your code.
Here is a version of your code working fine.
prime = [2]
i = 3
while len(prime) <= 1000:
testlist = []
for number in prime:
testlist.append(i % number)
if 0 not in testlist:
prime.append(i)
i = i + 1
print prime
I haven't tested but you can create method like below:
def get_prime_no_upto(number):
start = 2
primes = list(range(start,number)).to_a
for no in range(start,number):
for num in range(start,no):
if ( no % num == 0) and (num != no):
primes.delete(no)
break
primes
and can use it like
print primeno(100)
cheers!
def prime_checker(number):
stop = False
prime = True
n = 2
while stop == False and n < number:
if (number) % n == 0:
prime = False
stop = True
n += 1
if prime == True:
print("It's a prime number.")
elif prime == False:
print("It's not a prime number.")
prime_checker(11)