Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
This code is running for the 1-10 interval but for interval 20-30 it is writing 21 and 27 and I am unable to understand what's wrong in the code. I don't want to know other code; I want to know what's wrong in my code.
start = int(input("Enter the first number of the interval")) #starting of interval
end = int(input("Enter the last number of the interval")). #end of interval
for i in range(start, end+1):
for x in range (2,end):
if (i == 0 or i==1):
break
elif (i % x != 0):
print(i)
break
else:
break
for x in range (2,end):
if (i == 0 or i==1):
break
elif (i % x != 0):
print(i)
break
else:
break
This part of code should
print a number if it's prime, otherwise break
but it doesn't.
Do you notice something strange in your code? I do, and it's the fact that in every case the inner for loop breaks after the first iteration, rethink this aspect of your code, and it will work fine.
First, I am not sure whether you want the period after the inputting for the end. Also, your code checks if i is not divisible by x, then print. So for example, your code checks if 21 is divisible by 2. It is not, so your code prints it out and breaks.
Introduction
Your code is effectively testing if a number is odd and if it is, it prints it out.
If start is 1 and end is any number greater than 1, your code is printing every odd number greater than 2 in the interval [1, end].
It is printing all odd numbers, but not all odd numbers are prime!
Dissecting your code
Let's consider the [1, 20] interval. Your code outputs every odd number greater than 2 in the interval [1, 20].
3, 5, 7, 9, 11, 13, 15, 17, 19.
2 is prime and is missing from this list. We can fix that by writing the following within the outer loop but above the inner loop:
if i == 2:
print(i)
Now the output is `
2, 3, 5, 7, 9, 11, 13, 15, 17, 19.
This is better but 9, 15 are not prime numbers.
The if statement with condition (i == 0 or i == 1) inside of your inner loop is not causing any problems. Let's simplify the inner loop by moving this just outside of the inner loop (just above) so that your code becomes
for i in range(start, end+1):
if (i == 0 or i == 1):
# 0 and 1 are not prime
continue
if (i == 2):
# 2 is prime
print(i)
for x in range (2,end):
if (i % x != 0):
print(i)
break
else:
break
All that remains as the potential culprit for your problems is the inner loop so let's focus on that.
Whenever i is even, in the first iteration of the inner loop, we
have x = 2. We know that if i is even that i % 2 is 0 and so i % x != 0 is False and so we move onto the else, in which case we
break out of the inner for loop. This is all fine because no even
integer greater than 2 is prime!
Whenever i is odd, in the first iteration of the inner loop, we
have x = 2. We know that if i is odd that i % 2 is NOT 0 and so
i % x != 0 is True and then we print i and then break out of
the for loop.
We never once have x = 3 or x = 4 and so on!
The above describes precisely what you code is doing, which is ignoring even integers and simply printing out every odd integer.
Solution that outputs what you want
It would help me if I knew what definition of a prime number you have and/or what algorithm you are trying to implement. But since I don't have this information, I can only suggest a solution.
In order to solve your problem, you need to clearly have in mind what a prime number is. There are many equivalent definitions of a prime number (see the Wikipedia prime number page for examples of definitions). I chose a definition that suggests a natural algorithm for finding prime numbers. Whatever definition of prime number you were given, it is possible to prove mathematically that it is equivalent to this (for some this is the first definition of a prime number that they see!):
An integer i is prime if and only if i > 1 AND for all k in {2, 3,
..., i - 1}, i % k != 0.
In words this says that an integer i is prime iff i is strictly greater than 1 and for all integers k from 2 up until i - 1, k does not divide i evenly.
Here it is
start = int(input("Enter Start: "))
end = int(input("Enter End: "))
print(f"\nPrime numbers between [{start}, {end}]:")
for i in range(start, end + 1):
if (i == 0 or i == 1):
# i is not prime
continue
if (i == 2):
# i is prime
print(i)
continue
for x in range(2, i):
if (i % x) == 0:
break
if (i % x) != 0:
print(i)
Example session:
Enter Start: 20
Enter End: 30
Prime numbers between [20, 30]:
23
29
The (i == 0 or i == 1) check should be placed outside the inner for loop. Otherwise, for all i greater than or equal to 2, for every iteration in the inner loop, you will be checking to see if it is less than 2 or not. You are doing this check too much.
We know that when i == 2 that i is prime.
For i > 2, we appeal to the definition of a prime number above.
The inner loop and the last statement applies the second part of the prime definition.
Related
So, I wrote a code to find if a number is PRIME or NOT...
I wrote it in 2 different ways, they are almost same but I just had a doubt. So here it is:
1st code:
num = int(input("Enter the number: "))
lim = num//2 + 1
for i in range(2,lim):
if num % i == 0:
print("Prime!")
break
else:
print("Not Prime!")
2nd Code:
num = int(input("Enter the number: "))
for i in range(2,num):
if num % i == 0:
print("Prime!")
break
else:
print("Not Prime!")
The 1st code takes the input(num) and according to the input sets a limit(which is the half number + 1)
and then checks if the num is divisible by all the numbers in range (2 to lim)
The second one is same but instead of setting a limit it just checks all numbers lower than the input, which means it has to do a little more work...
Now both of these are almost same, the only difference is I saved a line in 2nd one and output efficiency is also better!
Which code would you want me to prefer/
also if this code has any problems, pointing them out would be helpful!
Thanks :)
Explanation
The most important piece of iteration, namely determining whether a number is prime or not, is to keep track of it. Without this process and in the OP's program, a variable is not used to handle this, meaning that he checks whether a number is or isn't prime every single time and concludes at that point. He also uses an else statement which is syntactically incorrect.
To prevent this, we can use a variable to keep track of this. Let's call it isprime. We need to assume that a number will always be a prime unless otherwise said. This can be achieved by setting isprime to default be True, and setting it to be False when we conclude that it is not a prime, because is has a divisor. Finally, we can check this variable at the end and determine whether that number is a prime or not, because it would be set to False if not, or left as True if it is.
Another observation made is that the limit for determining primes can be reduced down to sqrt(n). This is because we do not need to find every factor if it exists, just its lowest corresponding factor. Let's look at an example:
Factors of 24: 2, 3, 4, 6, 8, 12
We can stop checking for the factors right here:
2, 3, 4 | 6, 8, 12, 24
This is because if a number has a factor (such as greater than the square root), it will have a corresponding factor less than the square root. As a result, we can set our limit to be sqrt(n), just for peace of mind + a time complexity of O(sqrt(n)) v. O(n).
As an extra note, sqrt is not inbuilt into Python. You will have to import it from the math library using:
from math import sqrt
Final Code
# Setup
num = int(input("Enter the number: "))
lim = sqrt(num)
isprime = True
# Loop & check
for i in range(2,lim):
if num % i == 0:
isprime = False
break
# Results
if isprime:
print("Prime!")
else:
print("Not prime!")
The logic of the solution is wrong. You gave to switch the "Prime" and "Not Prime" tags. Like follows;
num = int(input("Enter the number: "))
lim = num//2 + 1
for i in range(2,lim):
if num % i == 0:
print("Not Prime!")
break
else:
print("Prime!")
The solution 1 is more efficient because you do not need to do extra
computation to check num//2 + 1. So it is preferable.
Sorry if my post is messy or hard to understand. I am just learning to code and to understand python. I have a homework where I am given n1 (random number from 0-10) and n2(from 30-45). My job is to print every number between n1 and n2 that is divisible by 2 but not by 3.
for x in range(n1,n2):
if x%2==0:
print(x)
if x%3==0:
continue
So this is my code now. I have tried it and it works, but it prints numbers like 6 and 12 that are divisible by 3. Hod do I fix it?
You just need to add an extra condition here:
for x in range(n1,n2):
if x % 2 == 0 and x % 3 != 0:
print(x)
Or to have the continue happen before the print such as:
for x in range(n1,n2):
if x%3 == 0:
continue
if x%2 == 0:
print(x)
What was happening was that you were printing first, and then checking the condition for divisibility by 3, which meant that even though you "skipped" the loop, you had already printed anyway.
You need to choose random number between 0-10 for n1 and 30-45 for n2. Import random module and use randint() to get random nos. Also, you can put both the conditions in same if statement. Your code:
import random
n1=random.randint(0,10)
n2=random.randint(30,45)
for i in range(n1,n2):
if i%2==0 and i%3!=0:
print(i)
p=[]
l=[]
v="run"
a=int(input("enter num or end: "))
while v!="end":
l.append(int(a))
a=input("enter num or end: ")
v=a
for a in l:
f=0
for j in range(2,a//2):
if a%j == 0:
f=1
break
if f==0:
p.append(a)
here I am inputting numbers and if its a prime number then I am putting it to list 'p' and at last output p.
i cant understand why 1st if statement not working when I am providing an even number like in picture below 4 is inputed so it should have changed value of f to 1 so that it doesn't get into list 'p' but its not. i am very new to python so there is possibility of silly mistakes.
on left code, on right output
The issue is that range(2, 4//2) is an empty range, since 4//2 = 2, and range(2, 2) includes every integer less than 2, starting with 2 - which is to say, no integers.
You will not have this issue with test numbers greater than 4, since in those cases you will always have at least 2 in the range of potential factors that you're testing.
It is because for 4 your statement:
for j in range(2, n//2):
becomes for j in range(2,2). if you have the same start and end in a range it does nothing. So it does not do the a % j and does not change f. In any case, if you are trying to check whether it is a prime number the range should be (2, int(n**0.5))
I am trying to create a program that prints out a list of numbers starting at 0 and leading up to a number the user inputs (represented by the variable "number"). I am required to use "while" loops to solve this problem (I already have a functional "for" loop version of the assignment). The program should mark anything in that list divisible by 3 with the word "Fizz," divisible by 5 with the word "Buzz," and anything divisible by both with "FizzBuzz" while also including unlabeled numbers outside of those specifications.
Every time I run this program, it ignores the conditions and just prints the word "FizzBuzz" however many times is represented by the number inputted. (I typically use 15 because it has at least one example of each condition, so that means I get 15 "FizzBuzz"s in a row).
To find out why it was doing that, I used print(i) instead of the rest of the program under the first conditional and it gave me 15 counts of the number 0, so there is reason to believe the program is completely ignoring the range I gave it and just outputting copies of i based on the user number input.
Any help would be appreciated!
number = int(input("Enter a Number"))
i = 0
while(i < number + 1):
if number % 3 == 0 and number % 5 == 0:
print("Fizzbuzz")
elif number % 5 == 0:
print("Buzz")
elif number % 3 == 0:
print("Fizz")
else:
print(number)
i += 1
print ("Done!")
You meant to check the divisibility of i, which increments every loop, not of number which doesn't change.
You also meant to print(i) in the else clause.
n = int(input("input n"))
prime = [2]
base = 3
order = 0
while base < n + 1:
if order < len(prime):
if base % prime[order] == 0:
order = len(prime)
else:
order += 1
else:
prime.append(base)
order = 0
base += 1
print (prime)
I am trying to create a list of prime numbers from 1 to given number 'n'.
(ignoring the case for numbers less than 3)
What I intend to do is:
bring first number from 3 to n (let's call this base)
compare base to first number in prime list (in this case, 2)
if the base is not divisible, compare this to next number in prime list.
repeat step 3 until all numbers in the prime list are compared or at least one number divisible to base in the prime list appears.
if base compared to all numbers in the prime list and is not divisible by any of them, append base to prime list.
increase the value of base by 1 and repeat step 2 to 5 upto base = n.
Whatever the value i put for n, i only get single value of 2 in the prime list printed. Please help to find out which part is wrong.
The reason your code is failing is because you are not actually checking through all of the stored prime numbers correctly - you need a second loop for this. Fortunately, Python makes this easy for you in two different ways: A list of values can be easily looped through, and else is supported by for. The modified code should look something like this:
n = int(input("input n"))
prime = [2]
base = 3
while base < n + 1:
for p in prime:
if base % p == 0:
# base is NOT a prime, break out
break
else:
# loop ran to completion
prime.append(base)
base += 1
print (prime)
So instead of some other if statement that doesn't quite do what you think it does, we instead use a for loop check all values in the prime list (assign that to p) and do the division as you might expect. If the modulus is 0, the loop breaks uncleanly and the else block will not run, and if none of the primes result in a modulus of 0 the else block will be triggered, adding that newly discovered prime number to the list and so on.
Example:
$ python3 foo.py
input n19
[2, 3, 5, 7, 11, 13, 17, 19]
If you wish to keep the existing logic (i.e. no for loops), you can do another while loop inside and remember to set order to 0 before it.