Program to find a specific prime number end in an infinite loop - python

Hey guys i have a problem i wrote this code for projecteuler to find a specific prime number but
it in ends in an infinite loop i looked it up and found many alternatives but want to understand why this code just dosent work. Im new to programing so if you also have any tipps to improve my code i will appreciate them.
import math
x = 1 #number that is getting checked
y = 0 #indicator of how many prime numbers found
a = 0 #the most recent prime number
while y < 6:
for i in range (2, int(math.sqrt(x))):
if (x % i ) == 0:
x = x + 1
break
else:
a = x
x = x + 1
y = y + 1
break
print (a)

You put x = 1, and then loop on a range starting from 2: so the for is never executed, and the while loops indefinitely. You need to start with x = 2, or to handle the special case of x = 1
EDIT
The code works for x at least 9: the for loop is never executed until int(math.sqrt(x)) is at least 3

Related

How do you find the first x prime numbers using python?

def xPrimes(x) :
y = 2
while y < x :
if isItPrime(y) == True :
y += 1
y += 1
print(primes)
I am a beginner in python and I'm having trouble having the program do what's needed. I also don't fully understand what my program does. When I did xPrimes(5), it gave me [2,3,5] instead of [2,3,5,7,11]. My code prints all prime numbers UP to x instead of x prime numbers. I suspect that I need a counter but I don't know where to implement it.
You just need to keep generating primes until you have x of them. If you're returning a list of the results, your counter is the length of that list.
def xPrimes(x: int) -> List[int]:
primes: List[int] = []
y = 1
while(len(primes) < x):
y += 1
if isItPrime(y):
primes.append(y)
return primes
Note that y is the prime number and x is the number of prime numbers and that these are completely different numbers. :)
What is primes here ?
you have to treat x as counter and do not compare with y as y is prime number not a counter
instead you can do something like this
def xPrimes(x) :
y = 2
index = 0
while index < x :
if isItPrime(y) == True :
y += 1
index+= 1
y += 1
print(primes)
you can see, I have use index as counter and incremented it when I got prime number
Homework is an adventure and chance to experiment!
First, you asked why xPrimes(5) gave you up to 5. You stop your loop when y < x, and y goes up each time. This shows you that you can get lost by using small variable names. You could make your code look like this by just renaming things:
def primes_up_to_number(stop_at) :
testing_number = 2
while testing_number < stop_at :
if isItPrime(testing_number) == True :
testing_number += 1
testing_number += 1
print(primes)
This is confusing to me, as you can't get the output [2, 3, 5]. When testing_number is 2, you add one to it, then add one again before you check isItPrime again, checking 4. I am assuming isItPrime updates some global array primes.
I think you want to change the code and meaning from stop_at to number_of_primes. If so, you should set a counter number_of_primes_found = 0 at start of the function and add one to it each time you find a prime. You should change the expression in the while loop to keep looping until that number of primes is found.
Have a great day! Keep coding! Keep notes.

Sum of all prime numbers between 1 and N in Python

I'm new to programming. While trying to solve this problem, I'm getting the wrong answer. I checked my code a number of times but was not able to figure out the mistake. Please, help me on this simple problem. The problem is as follows:
Given a positive integer N, calculate the sum of all prime numbers between 1 and N (inclusive). The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains one line of input containing N. For each testcase, in a new line, print the sum of all prime numbers between 1 and N.
And my code is:
from math import sqrt
sum = 0
test = int(input())
for i in range(test):
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(max)) + 1
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
print(sum)
For input 5 and 10, my code is giving output 6 and 48 respectively, while the correct answer is 10 and 17 respectively. Please, figure out the mistake in my code.
Here, I implemented simple program to find the sum of all prime numbers between 1 to n.
Consider primeAddition() as a function and ip as an input parameter. It may help you to solve your problem.Try it.
Code snippet:
def primeAddition(ip):
# list to store prime numbers...
prime = [True] * (ip + 1)
p = 2
while p * p <= ip:
# If prime[p] is not changed, then it is a prime...
if prime[p] == True:
# Update all multiples of p...
i = p * 2
while i <= ip:
prime[i] = False
i += p
p += 1
# Return sum of prime numbers...
sum = 0
for i in range (2, ip + 1):
if(prime[i]):
sum += i
return sum
#The program is ready... Now, time to call the primeAddition() function with any argument... Here I pass 5 as an argument...
#Function call...
print primeAddition(5)
This is the most broken part of your code, it's doing the opposite of what you want:
res = x%y
if res==0:
sum = sum + x
break
You only increment sum if you get through the entire loop without breaking. (And don't use sum as you're redefining a Python built-in.) This can be checked using the special case of else on a for loop, aka "no break". I've made that change below as well as corrected some inefficiencies:
from math import sqrt
T = int(input())
for _ in range(T):
N = int(input())
sum_of_primes = 0
if N < 2:
pass
elif N == 2:
sum_of_primes = 2
else:
sum_of_primes = 2
for number in range(3, N + 1, 2):
for odd in range(3, int(sqrt(number)) + 1, 2):
if (number % odd) == 0:
break
else: # no break
sum_of_primes += number
print(sum_of_primes)
OUTPUT
> python3 test.py
3
5
10
10
17
23
100
>
A slight modification to what you have:
from math import sqrt
sum = 0
test = int(input())
max = int(input())
for x in range(test,max+1):
if x == 1:
pass
else:
half = int(sqrt(x)) + 1
for y in range(2,half):
res = x%y
if res==0:
break
else:
sum = sum + x
print(sum)
Your biggest error was that you were doing the sum = sum + x before the break rather than outside in an else statement.
PS: (although you can) I'd recommend not using variable names like max and sum in your code. These are special functions that are now overridden.
Because your logic is not correct.
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
here you check for the factors and if there is a factor then adds to sum which is opposite of the Primes. So check for the numbers where there is no factors(except 1).
from math import sqrt
test = int(input())
for i in range(test):
sum = 0
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(x)) + 1
if all(x%y!=0 for y in range(2,half)):
sum = sum + x
print(sum)
First of all, declare sum to be zero at the beginning of the for i loop.
The problem lies in the if statement at almost the very end of the code, as you add x to the sum, if the res is equal to zero, meaning that the number is indeed not a prime number. You can see that this is the case, because you get an output of 6 when entering 5, as the only non-prime number in the range 1 to and including 5 is 4 and you add 2 to the sum at the beginning already.
Last but not least, you should change the
half = int(sqrt(max)) + 1
line to
half = int(sqrt(x)) + 1
Try to work with my information provided and fix the code yourself. You learn the most by not copying other people's code.
Happy coding!
I believe the mistake in your code might be coming from the following lines of code:
for x in range(3,max+1):
half = int(sqrt(max)) + 1
Since you are looping using x, you should change int(sqrt(max)) to int(sqrt(x)) like this:
for x in range(3,max+1):
half = int(sqrt(x)) + 1
Your code is trying to see if max is prime N times, where you should be seeing if every number from 1-N is prime instead.
This is my first time answering a question so if you need more help just let me know.

Simple python program ran into infinite loop

I am trying to make a simple XOR program. Once I finished checking my syntax, I ran my program and ran into an infinite loop. I can't find my error. Help?
def disencode(n):
seconde = raw_input("Input_Second_String")
y = len(n)
x = 0
while x < y:
if n[x] == seconde[x]:
print 0
else:
print 1
x =+1
disencode(raw_input("Input_First_String"))
x=+1 should be x += 1, as with your current code, you never increment x,
as x =+ 1 is the same thing as x = 1.
You're effectively setting x as 1, never increasing it, and asking the loop to run while x < y, which is infinite.
See here for more information
use x += 1 for incrementing x instead of x =+1

for loop stuck and not interating (Python 3)

I'm currently working on a small script that aims to find taxicab numbers. There is only one small problem, the for loop doesn't increment the variable x and is stuck looping forever. I'll paste the relevant part of the code below:
n = int(10)
counter = int(0)
m = int(m)
x = int(1)
y = int(n**(1/3))
cheatsheet = []
while counter in range(0,m):
for x in range(1,y):
if x**3 + y**3 < n:
print('less than')
print(x,y,n)
continue
elif x**3 + y**3 > n:
print('greater than')
y -= 1
continue
elif x > y:
if n in cheatsheet:
print('counting')
counter = counter+1
#checking if n occurs in the list, if so it will add 1 to the counter so that the program will know when to stop
n = n + 1
y = int(n**(1/3))
x = 1
print('break1')
#resetting values and bumping n so that it will continue the quest to find 'em all
break
else:
if x and y == 1:
#this is an error correction for low n values, i mean really low it might be redundant by now
n = n + 1
y = int(n**(1/3))
x = 1
print('break2')
break
cheatsheet.append((n,x,y))
print(cheatsheet)
This yields the following result in a terminal window:
image
Note that I killed the process by myself, the program did not.
As you can tell, the script just loops around and prints 'less than' and the values for x,y,n.
Help is greatly appreciated!
EDIT: the variable m is given by the user, but not included in this bit of code.
This has a number of issues wrong with it I'm not willing to post functional code but I will point some of the issues out.
For starters:
n = int(10)
isn't required, not an error but redundant. Use n = 10 with the same effect.
Then:
while counter in range(0,m):
will always evaluate to True. m is *never modified so the membership test always succeeds, maybe you need to re-evaluate your looping.
for x in range(1,y):
This will assign x the value 1 all the time. y evaluates to 2 by your arithmetic (int rounds floats to the floor, i.e int(2.9) -> 2) so either use math.ceil or add one to your y.
Appart from that you re-assign variable names all the time inside your loops, that's confusing and might lead to unexpected behavior.

While loop creating

I am writing a program in Python that defines a function that takes a single argument. The function has to be a while loop the returns the largest power of 16 that it is equal to. However, I am not sure how to write the while loop.
Python Docs
while True:
n = input("Please enter 'hello':")
if n.strip() == 'hello':
break
so, in layman's terms
while <condition>:
...
I couldn't completely understand your question but here's how to do a while loop to get the x to the 16th power of an input:
def loop_function(x):
y = 1
start = x
while y != 16:
result = start * x
start = result
y += 1
return result
print loop_function(3)
The above code will return the answer to 3^16 which is 43046721
You can even make this a broader function two arguements
def loop_function(x, y):
z = 1
start = x
while z != z:
result = start * x
start = result
z += 1
return result
print loop_function(3, 2)
The above code will return 9 i.e 3^2

Categories

Resources