for loop stuck and not interating (Python 3) - python

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.

Related

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

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

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.

Printing prime factors of a number using a "points system"

We've been given a challenge to write a program that prints prime factors of an input number. We're given an outline: the program checks for factors of the original number; each such factor gets one point. Then, if that factor is prime, it gets another point. Each factor with two points gets printed.
Here's what I have so far.
print('Please enter a number')
x = int(input('Number:'))
a = int(0)
b = int(0)
c = int(1)
d = int(0)
counter = int(0)
while (a < x-1):
a = a + 1
counter = 0
if (x / a % 1 == 0):
b = a
counter = counter + 1
while(c < b - 1):
c = c + 1
if((b / c) % 1 != 0):
d = b
counter = counter + 1
if(counter == 2):
print(d)
With input of 15, I get 3 and 5, but also 15 (wrong). With 24, I get 3, 4, 6, 8, and 12; several of these are not prime.
I believe the issue lies somewhere in the innermost loop, but I can't pinpoint the problem.
At first the issue was I wasn't resetting the "counter", so future factors would exceed 2 "points" and nothing would print. I fixed that by resetting it before it enters the innermost loop, but sadly, that didn't fix the problem.
I've also tried getting rid of 'b' and 'd' and just using two variables to see if I was somehow overcomplicating it, but that didn't help either.
EDIT: Edited slightly for clarity.
Your first sentence was enough of a clue for me to unravel the rest of your posting. Your main problems are loop handling and logic of determining a prime factor.
In general, I see your program design as
Input target number
Find each factor of the number
For each factor, determine whether the factor is prime. If so, print it.
Now, let's look at the innermost loop:
while(c < b - 1):
c = c + 1
if((b / c) % 1 != 0):
d = b
counter = counter + 1
if(counter == 2):
print(d)
As a styling note, please explain why you are building for logic from while loops; this makes your program harder to read. Variable d does nothing for you. Also, your handling of counter is an extra complication: any time you determine that b is a prime number, then simply print it.
The main problem is your logical decision point: you look for factors of b. However, rather than waiting until you know b is prime, you print it as soon as you discover any smaller number that doesn't divide b. Since b-1 is rarely a factor of b (only when b=2), then you will erroneously identify any b value as a prime number.
Instead, you have to wait until you have tried all possible factors. Something like this:
is_prime = True
for c in range(2, b):
if b % c == 0:
is_prime = False
break
if is_prime:
print(b)
There are more "Pythonic" ways to do this, but I think that this is more within your current programming sophistication. If it's necessary to fulfill your assignment, you can add a point only when you've found no factors, and then check the count after you leave the for loop.
Can you take it from there?
I'm not entirely sure I follow you're problem description, but here is my attempt at interpreting it as best I can:
import math
def is_factor(n,m):
return m % n == 0
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def assign_points(n):
for i in range(1,n+1):
if is_factor(i,n) and is_prime(i):
print('two points for: ', i)
elif is_factor(i,n):
print('one point for: ', i)
print(assign_points(15))

Python 101 and Math Logic - Listing square root numbers less than n

I'm stuck on a Python 101 type problem involving loops. Here are the directions:
The square numbers are the integers of the form K × K, e.g. 9 is a square number since 3 × 3 = 9. Write a program that reads an integer n from input and outputs all the positive square numbers less than n, one per line in increasing order. For example, if the input is 16, then the correct output would be
1
4
9
This is what I have so far but it sort of works but runs on forever. My code never reaches the if statement so it breaks(stops) before it gets to 17.
Suppose n = 17.
n=int(input())
counter = 1
while counter * counter < n:
for counter in range(1,n):
a = counter*counter
print(a)
if a < n:
break
Results:
1
4
9
16
25
36
49
64
81
Here is a correction of your code.
n=int(input())
counter = 1
for counter in range(1,n):
a = counter*counter
if a >= n:
break
print(a)
There were three things wrong with your code. First, the condition you want to break on is a >= n not a < n. Second, that condition needs to be tested before you print the number. Thus the if statement needs to be inside the for loop and before your print, statement. Third, the outer while loop is not really necessary :) Though you can add it, but a simple inner for loop will suffice.
if a < n: will never succeed unless n = 2; because inside the loop a is becoming (n-1)*(n-1) which is greater than n for n > 2; that's why the infinite loop. Try this:
>>> counter = 1
>>> n = 16 # int(input())
>>> r = counter**2
>>> while r<n:
print r
counter += 1
r = counter**2
1
4
9
Or just modify yours one by removing the outer loop, and placing the conditional inside the for loop like:
for counter in range(1,n):
a = counter*counter
if a >= n:break
print(a)
Your code loops might be the case in you semantics error try this out light on the memory and simple
def number(n):
for i in range(0,n):
w=i*i
if w>n-1:
break
print(w)
number(144)
You've got three issues here, but, as you can tell, you're on the right track.
First off, you're using two loops when you only need to be using one, and I think it's because you're a little unclear as to how the while loop works. The while loop checks that the condition is true before each time it runs. If the condition becomes false while going through the loop, the loop will still finish - it just won't start another. For example:
n = 17
while n < 18:
n += 1
print n
n += 1
print n
prints:
18
19
In your case, each iteration through the while loop creates a for loop. In order for a single iteration through the while to take place, your computer has to go through for every number from 1 to n, meaning that it'll print out all those extra numbers before your while loop even has a second chance to do its check. The easiest way to fix this is to remove the while loop and structure your code a little differently. As I'll show you in a few lines, you don't really need it.
When you say if a < n:, you've got your sign backwards and you need an equals sign. The problem asks that you give all values less than n, but, without the =, the program won't stop until it's greater than n. It should be if a >= n:.
Finally, the order of the operations isn't what you want it to be. You'd like it to check that a is less than n before printing, but you print before you do that check. If you switch them around, you'll get something like this:
n=int(input())
for counter in range(1,n):
a = counter*counter
if a >= n:
break
print(a)
which should do the trick.
What about
n= int(input())
counter= 1
while counter * counter < n:
print( counter * counter )
counter+= 1
?
Turtle man was perfect but for me. I needed to be able to get all the way to 100 so if you need to get past 81 do this
n = int(input())
counter = 1
for counter in range(1,n + 1):
a = counter*counter
if a > n:
break
print(a)

Categories

Resources