Finding the 1000th prime number (python) debug - python

I am attempting to write a code to calculate the 1000th prime number and I'm running into an issue with my loop counter that i don't understand.
prime_test = 1
count=0
for count in range(0,1001):
for divisor in range(2,prime_test):
if (prime_test % divisor) == 0:
break
else:
print(prime_test)
count += 1
prime_test+=1
Could someone please explain why the above code is dysfunctional? The problem is that the count variable iterates at the same rate as the prime_test variable. How do I separate the two such that count only increases when a new prime is found and not when the loop is engaged?

Don't use for count in range(0, 1001):. That just increments count sequentially, not when it finds a prime. Use a while loop.
prime_test = 2
count = 0
while count < 1000:
for divisor in range(2,prime_test):
if (prime_test % divisor) == 0:
break
else:
print(prime_test)
count += 1
prime_test += 1
You also should start prime_test at 2, not 1, since 1 isn't a prime number, but your algorithm will say it is.

One more answer as the same thing might need to be repeated thousand times before it could be understood.
Setting the value of c before the loop has no effect at all and the new to c within the loop assigned value will be overwritten by next loop loop as c will be set to the next value provided by range(). Python for c in range() loops are not like loops in some other programming languages. So every newbie has to go through this ... wondering how it comes.
Following code demonstrates this:
c = 100
for c in range(5):
print(c, end=' -> ')
c = c + 5
print(c)
printing
0 -> 5
1 -> 6
2 -> 7
3 -> 8
4 -> 9
If you change your code to:
prime_test = 2
counter=0
for count in range(0,11):
for divisor in range(2, prime_test):
if (prime_test % divisor) == 0:
break
else:
print(prime_test)
counter += 1
prime_test+=1
print(f'{counter=} , {prime_test=} ')
you will get as output:
2
3
5
7
11
counter=5 , prime_test=13

Related

A program that finds all four of the perfect numbers that are less than 10000

everyone.
I have a question about an exercise from Brian Heinold's A Practical Introduction to
Python Programming that reads "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 ΜΈ= 1 + 3 + 5. Write a program that finds all four of the perfect numbers."
I'm a beginner. I tried. My code doesn't work. Please tell me where did I go wrong and why does the program print the number 1 endlessly why I press Run.
Thank you.
# We have to check all numbers from 1 to 10000.
for i in range(1,10001):
# Since all numbers are divisible by 1,
#we can set 1 as the initial value.
sum_div = 1
#The potential divisors also range from 1 to 10000,
#therefore we can use this nested loop:
for j in range(1,20001):
# A j value can be a divisor if the remainder is zero.
# AND the range of the divisors must not include the number itself.
# Since 1 is already known to be a divisor, we can start checking from 2.
if i % j == 0 and j != i:
#We already have 1 as the first divisor,
#so now we have to add the other divisors.
sum_div = sum_div + j
#If the sum of the divisors equals the number,
#then we got the number we need.
if sum_div == i:
print(i)
The j for loop should be from 2 to i-1 not 1 to 20001 and your if logic should be outside j for loop indicating we are done with counting sum
# We have to check all numbers from 1 to 10000.
for i in range(1,10001):
# Since all numbers are divisible by 1,
# we can set 1 as the initial value.
sum_div = 1
# The potential divisors also range from 1 to 10000,
# therefore we can use this nested loop:
for j in range(2, i):
# A j value can be a divisor if the remainder is zero.
# AND the range of the divisors must not include the number itself.
# Since 1 is already known to be a divisor, we can start checking from 2.
if i % j == 0 and j != i:
# We already have 1 as the first divisor,
# so now we have to add the other divisors.
sum_div = sum_div + j
# If the sum of the divisors equals the number,
# then we got the number we need.
if sum_div == i:
print(i)
At first glance, the reason your code is printing 1 endlessly is because you're comparing sum_div and i within the loop that iterates through j. if sum_div == i needs to be an indentation level higher than it currently is.
Secondly, because you've already considered 1 as a divisor when initializing sum_div, you do not need to start j from 1. It can start from 2.
Divisors will always be less than the number you're checking for, so you do not need j to loop from 1 to 20001 - it's enough to check till the value of i.
The value of i can start from 2, because we're not interested in whether 1 is a perfect number or not.
Based on these observations, here's the modified snippet that works for me.
for i in range(2, 10001):
sum_div = 1
for j in range(2, i):
if i%j == 0 and j != i:
sum_div += j
if sum_div == i:
print(i)
print("End of program")
Hope this helps!

Python - My query to extract prime numbers does not work

I am attending a course on Udemy and one of the exercises is to return all the prime numbers from a range of numbers (for example all prime numbers before 100)
This is the query that the teacher made
def count_primes2(num):
#Check for 1 or 0
if num < 2:
return 0
######################
#2 or greater
#Store our prime numbers
primes = [2] #I start my list with 2 that is a prime number
#Counter going up to the input num
x = 3 #I create a variable on which I will continue adding until I reach num
# x is going through every number up to the input num
while x <= num:
#Check if x is prime
for y in range(3,x,2): # for y in range from 3 to x in even steps, we only wantto check odd numbers there
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
count_primes2(100)
However, I came up with the one below that is not working. My idea is:
Given each number i between between 3 and num+1 (for example 100 would be 101 so that 100 can be included in the calculation):
Open a for loop in which I divide i by each number g before i (including i) and I have a counter checking when this division gives no remainder. This implies that in case of prime numbers the counter should always be 2 (for example 3--> 3:1 and 3:3 would give remainder 0).
If the counter is equal to 2, then i is a prime and I want to append it to the list.
I am not using any while loop in my query. Can you help me to identify why my query is not working?
def count_prime(num):
counter=0
list_prime=[2]
if num<2:
return 0
for i in range(3,num+1):
for g in range(1,i+1):
if i%g==0:
counter+=1
if counter==2:
list_prime.append(i)
return list_prime
count_prime(100)
Kudos to Khelwood for the help. Below the working query:
def count_prime(num):
counter=0
list_prime=[2]
if num<2:
return 0
for i in range(3,num+1):
for g in range(1,i+1):
if i%g==0:
counter+=1
if counter==2:
list_prime.append(i)
counter=0
return list_prime
count_prime(100)
you may do this :
for i in range(2,num):
if (num % i) == 0:`
Instead of using two for loops, you can simply eliminate one of the for loop and do this, I hope this may work for you.
thankyou.

Looking for Clarification on how this "For-Loop" works

I'm a complete beginner to programming so forgive me for my naivete.
I wanted to make a program in Python that lets me print a given N number of prime numbers, where N is inputted by the user. I searched a little on "for/while" loops and did some tinkering. I ran a program I saw online and modified it to suit the problem. Here is the code:
i = 1
print("Hi! Let's print the first N prime numbers.")
nPrimes = int(input("Enter your N: "))
counter = 0
while True:
c = 0 #another initialization
for x in range (1, (i + 1)):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
if c == 2:
print(i, end = " ")
counter = counter + 1
if counter > = nPrimes: #if it reaches the number input, the loop will end.
break
i = i+1
print(": Are your", nPrimes, "prime number/s!")
print()
print("Thanks for trying!")
This should be able to print the amount of prime numbers the user so likes. It is a working code, though I am having difficulty trying to understand it. It seems that the variable c is important in deciding whether or not to print the variable i (which in our case is the supposed prime number during that interval).
We do c + 1 to c every time our variable a has a remainder of 0 in a = i % x. Then, if c reaches 2, the current variable i is printed, and variable c re-initializes itself to 0 once a prime number has been found and printed.
This I can comprehend, but I get confused once the numbers of i get to values 4 and onwards. *How is 4 skipped by the program and not printed when it has 2+ factors in the range that makes its remainder equal to zero? Wouldn't c == 2 for 4 and thus print 4? *And how would the program continue to the next number, 5? (Given that variable N is a large enough input).
Any clarifications would be greatly appreciated. Thank you so much!
From Wikipedia we know:
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
So to find a prime, is to find a natural number, aka an integer, which can only be exactly divided by 1 or itself. This is called Approach of Definition to find primes.
Hence, the following loop traverses through all integers from 1 to i,
and it counts how many times the integer i can be exactly divided by them.
for x in range (1, (i + 1)):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
And later you judge if the integer i can only be exactly divided by 1 and itself.
If true, you got a prime;
otherwise you just keep on.
if c == 2:
print(i, end = " ")
counter = counter + 1
if counter > = nPrimes: #if it reaches the number input, the loop will end.
break
Meanwhile, you can improve this prime searching algorithm a little bit by changing i = 1 to i = 2 in the beginning and adding an if statement:
# Start from 2 instead of 1
# and end at `i - 1` instead of `i`
for x in range (2, i):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
# Abandon the loop
# because an integer with factors other than 1 and itself
# is unevitably a composite number, not a prime
if c > 0:
break
if c == 0:
print(i, end = " ")
counter = counter + 1
if counter >= nPrimes: #if it reaches the number input, the loop will end.
break
This twist improves the efficiency of your program because you avoid unnecessary and meaningless amount of work.
To prevent potential infinite loop resulting from while expression,
you should replace while True: with while counter < nPrimes:. And the code turns out to be like this:
#if it reaches the number input, the loop will end.
while counter < nPrimes:
c = 0 #another initialization
# Start from 2 instead of 1
# and end at `i - 1` instead of `i`
for x in range (2, i):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
# Abandon the loop
# because an integer with factors other than 1 and itself
# is unevitably a composite number, not a prime
if c > 0:
break
if c == 0:
print(i, end = " ")
counter = counter + 1
i = i + 1
If you want to read more about how to improve your program's efficiency in finding primes, read this code in C language. :P
c in this case is used to count the number of numbers that divide evenly into i.
for example, if i = 8: 8 is divisible by 1, 2, 4, and 8. so c = 4 since there are 4 things that divide evenly into it
if i = 5: 5 is divisible by 1 and 5. so c = 2 since there are 2 numbers that divide evenly into it
if i = 4 (where you seem to be confused): 4 is divisible by 1, 2, and 4. so c = 3, not 2.

My Code for Perfect Number

So far, I've learned about for loops, if statements, and counting so it would be great to get feedback using only these topics. I was trying to solve the Perfect Number problem where the divisors excluding the number add up to that number. So for 6, The divisors 1,2,3 add up to 6. I've tried looking at other posts, but I wanted to know why my code specifically isn't working. I've tried solving the problem, and I feel that I'm almost there. I just have one issue. This is what I have so far:
#
num = 30
for i in range(1,num+1):
count = 0
for k in range(1,num+1):
if i%k == 0 and i!=k:
count += k
if count == i:
print(k,'Perfect',i)
#
The output on shell gives me this:
3 Perfect 6
8 Perfect 24
14 Perfect 28
#
I know that 24 is not a perfect number. The highest divisor for 24 excluding 24 should be 12, but I'm getting 8. This is why it's showing me that 24 is perfect. Can anyone clarify why I'm not able to get 12?
You have to count all divisors, before you make a conclusion, your code goes up to 8 for 24, then sums up all divisors so far and declares 24 a perfect number, not waiting for other divisors to appear.
Your code should looks like this:
for i in range(1,num+1):
count = 0
for k in range(1,i): # no point searching for numbers greater than i
if i%k == 0 :
count += k
if count == i:
print('Perfect',i)
and produce:
('Perfect', 6)
('Perfect', 28)
Your problem is that you're checking whether count == i in the wrong place. You need to check after the entire count summation is finished, not after each addition to the count sum.
num = 30
for i in range(1,num+1):
count = 0
for k in range(1,num+1):
if i%k == 0 and i != k:
count += k
if count == i:
print(k,'Perfect',i)
Also, if you want slightly more efficient code, you could do the subtraction afterwards instead of checking each value. Also, as lenik suggested, you only need to count to i (since i can't have any divisors larger than itself.) Even more efficiently, one could just use a Sieve of Eratosthenes-like approach, and count to sqrt(i)+1, finding the corresponding factors along the way:
from math import sqrt
num = 30
for i in range(1,num+1):
count = 0
for k in range(1,sqrt(i) + 1):
if i%k == 0:
count += k
factor = count/k
# The conditional is necessary in case i is a perfect square.
if k != factor:
count += factor
if count - i == i:
print(k,'Perfect',i)
12 is not perfect 1 + 2 + 3+ 4 + 6 != 12
second for also have problem in count (change it to i+1)
and critical problem was las check was in for
num = 30
for i in range(1,num+1):
count = 0
last = 0
for k in range(1,i):
if i%k == 0:
count += k
last = k
if count == i:
print(last,'Perfect',i)
result :
3 Perfect 6
14 Perfect 28

Why does this code not go to an infinite loop? (Python)

I'm currently beginning to learn Python specifically the while and for loops.
I expected the below code to go into an infinite loop, but it does not. Can anyone explain?
N = int(input("Enter N: "))
number = 1
count = 0
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
For this code to not infinitely loop, count needs to be >= N.
For count to increase, x needs to be equal to 2.
For x to be equal to 2 the inner for loop needs to run twice:
for i in range(1, number+1):
if number % i == 0:
x = x + 1
For the inner for loop to run twice number must not have factors besides 1 and the number itself. This leaves only prime numbers.
The inner loop will always set x == 2 when number is a prime number. As there are an infinite amount of prime numbers, count >= N will eventually be satisfied.
Try to change N to number:
while count < N:
while count < number:
Ok let's dissect your code.
N = int(input("Enter N: "))
number = 1
count = 0
Here you are taking user input and setting N to some number,
for the sake of brevity let's say 4. It gets casted as an int so it's now
an integer. You also initialize a count to 0 for looping and a number variable holding value 1.
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
Here you say while count is less than N keep doing the chunk of code indented.
So in our N input case (4) we loop through until count is equal to 4 which breaks the logic of the while loop. Your first iteration there's an x = 0 this means everytime you start again from the top x becomes 0. Next you enter a for loop going from 1 up to but not including your number (1) + 1 more to make 2. you then check if the number is divisible by whatever i equals in the for loop and whenever that happens you add 1 to x. After iteration happens you then check if x is 2, which is true and so you enter the if block after the for loop. Everytime you hit that second if block you update count by adding one to it. now keep in mind it'll keep updating so long as that if x == 2 is met and it will be met throughout each iteration so eventually your while loop will break because of that. Hence why it doesn't go forever.

Categories