checking prime number in python - python

i wrote this program to check weather the no. is prime or not but it shows the number is prime multiple times. how can i solve it
To check weather the number is prime or not.
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
break
else:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')

Here is my code to check whether a number is prime or not, hope it helps
# Program to Check whether given number is prime
def isPrime(number):
limit = int(number/2) # limit indicates how many times we need to run the loop
flag=0 # to keep track whether the number is prime or not
if number==0 or number==1:
print(f"The Given Number {number} is Not Prime")
return
for i in range(2,limit+1):
if number%i==0:
flag=1
break
if flag==0:
print(f"The Given Number {number} is Prime")
else:
print(f"The Given Number {number} is Not Prime")
isPrime(1)

Your problem is that the else part of your for-loop is wrong. You print "the number is prime" every time a division check fails, not just at the end.
I added an isPrime boolean that tracks if a single check failed. Only if none of them fail, you can print that the number is prime.
num = int(input("please enter the number you want to check\n"))
if num > 1:
isPrime = True
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
isPrime = False
break
if isPrime:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
You can simplify that even more, with a construct of python called for-else (credits to #TheGamer007):
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
break
else:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
It works because Python's for-loops can have an else: following, which only triggers if you don't break out of the loop.
This might be exactly what you were trying to do. In that case, all you did wrong was your indentation.
Also, from an algorithmical point of view, there are much better ways to check. A first simple improvement is that you don't need to check range(2,num), but only range(2, int(math.sqrt(num))+1)

All you need in order to determine whether a number is prime or not, is to find 1 number that is greater or equal to 2 that divides the number.
In your loop, you print out a message that says "the number is prime" for each number that does not divide the given number.
For example, if you want to check whether the number 9 is prime or not, you will loop all numbers from 2 to 8 and check if they can divide 9. So in your for loop, the number 5 for instance -> 9%5 != 0 -> "the number is prime" message will pop up, which is wrong.
The code below shows how you can use a boolean to rise up a flag when the number is NOT prime.
num = int(input("please enter the number you want to check\n"))
isPrime = True
while num < 1:
int(input("enter a positive value\n"))
if num == 1:
print("the number is not prime")
return
for i in range(2, num):
if (num % i) == 0:
isPrime = False
break
print(str(num) + " is prime? " + str(isPrime))

Use a variable, for example flag and initialize it to 0. If the number is not prime,i.e i%2==0 set flag to 1 and break, else flag = 0 .
After that come out of the for block, and with the help of if condition display the number is prime or not. That is if flag==0 the number is prime else not.

I would suggest the following implementation
We only need to check/loop up to a square root of the number and not the number itself and is thus faster.
The for-else structure gets you rid of the isPrime flag that you otherwise need. The way this works is that if the loop finishes normally without breaking (meaning you haven't found what you are looking for) it goes into the else
import math
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, int(math.sqrt(num))+1):
if (num % i) == 0:
print("the number is not prime")
print(i, "times", num//i, "is", num)
break
else:
print("the number is prime")
else:
print("the number is not prime")

One way to do it:
def is_prime(n):
count = 0
if x > 1:
for i in range(1, n + 1):
if x % i == 0:
count += 1
return count == 2
number = int(input("Insert a number: "))
if is_prime(number):
print(str(number) + " is a prime number")
else:
print(str(number) + " is not a prime number!")
is_prime(7) # >> Returns True
How does it work:
A prime number (n) must fullfill the following rules:
n > 1;
n divisible only to 1 and itself(
n % 1 == 0,
n % n == 0)
Perform the modulus operation from 1 to n iteratively. Increment the variable count
every time the result is 0. If the input satisfies the 2nd condition from above then count should be equal 2. If count equals 2 then the number is prime.
Ex:
is_prime(7): 7 % 1 = 0 (count += 1), 7 % 2 = 1, 7 % 3 = 1, 7 % 4 = 3, 7 % 5 = 2, 7 % 6 = 1, 7 % 7 = 0 (count += 1); >> 7 is prime

Related

How to print only the last result of an array of sum in python

I want to calculate the sum of the natural numbers from 1 up to an input number. I wrote this code:
number=int(input("enter a natural number"))
if number<0:
print("The number is not positive")
else:
n=0
for i in range (1,number+1):
n+=i
print(n)
But it prints multiple numbers instead. For example, if the user puts five, the program should print 15, but I get this:
1
3
6
10
15
How can I fix the code so that only 15 appears?
You have all the steps because your print statement is in your for loop.
Change it like this:
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
result = 0
for i in range(1, number + 1):
result += i
print(result) # We print after the calculations
There's also a mathematical alternative (see here):
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
print(number * (number + 1) / 2)
As I've pointed out and suggested earlier in comments, you could move the print statement out of for-loop to print the final sum.
Or you could try to use generator expression to get all number's total (sum), because we don't care the intermediate sums.
This simple sum of all up to the number in one shot.
number=int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
# exit or try again <---------
else:
print(sum(range(1, number + 1))) # given 5 -> print 15
Something like this?
number = int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
else:
n = 0
for i in range (1,number + 1):
n += i
print(n)
The answer to your question is that you are printing the n every time you change it. You are looking for the last answer when you run the code. This code should solve it.
number = int(input("enter a natural number"))
if number < 0:
print("The num < 0")
else:
n = 0
l = []
for i in range (0, number+1):
n+=i
l.append(n)
print(l[len(l)-1])

Python Problem Take input N from the user Print 'EVEN' for every even number Print 'ODD' for every odd number, from 1 to N

enter image description hereEven Numbers!
Take input N from the user and print EVEN for every even number and ODD for every odd number between 1 and N.
Sample Input 1:
4
Sample Output 1:
ODD
EVEN
ODD
EVEN
You need to use the modulus opperator which is % in python to check if the number is odd or even.
N = int(input("Enter a number: "))
i = 1
while(i <= N):
if (i % 2) == 0:
print('EVEN')
else:
print('ODD')
i += 1
N = int(input())
for i in range(1,N+1):
if i%2 == 0:
print("EVEN".format(i))
else:
print("ODD".format(i))

How to stop python printing more than one line?

I have a small function to check if a number is prime or not. It works fine apart from one small detail - it prints out more than one print line on the program end.
n = int(input("Enter a number to find if it is prime: "))
def is_prime():
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("The number {} is prime".format(n))
is_prime()
If I enter the number 2 for e.g. when the program runs, it prints:
the number 2 is prime
the number 2 is prime
the number 2 is prime
It only needs to print the line once, so why is this?
Your else is in the wrong position. You have it on the if, but you actually want it on the for.
It might not be well known, but you can have a else on for-loops and it will execute if no break was executed during the loops.
n = int(input("Enter a number to find if it is prime: "))
def is_prime():
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("The number {} is prime".format(n))
is_prime()

Split a number into 3 parts

If there is number I want to split that number into 3 parts.
for example: num = 4563289
these have to split into 45 63 289
I just count the numbers.
count = 0
num = int(raw_input("enter the number :"))
while (num > 0):
num = num//10
count = count + 1
print ("Total number of digits:", count)
if count % 2 == 0:
print('even')
else:
print('Odd')
Using this code to identify whether it is odd or even.
Based on that i want to split the numbers into 3 parts.
Make the integer string and find its length. Something like this:
num = 4563289
num_str = (str(num))
a = int(len(num_str) / 3)
print('{} {} {}'.format(num_str[:a], num_str[a:2*a], num_str[2*a:]))
(result is 45 63 289)
Assuming your indentation is supposed to look like this:
count = 0
num = int(raw_input("enter the number :"))
while (num > 0):
num = num//10
count = count + 1
print ("Total number of digits:", count)
if count % 2 == 0:
print('even')
else:
print('Odd')
By the end, you cant split the number anymore, because it has been modified in the while-loop until it is 0. If you run it and let the program print the num variable at the end it always comes out as 0 because that is what you are telling the program to do. In my opinion its never a good idea to modify the original variable especially as its not easily retrievable.
Anyway, theres an easer way to tell whether the number of digits is odd or even, using the len() function:
num = int(raw_input("enter the number :"))
num_str = str(num)
print ("Total number of digits: " + str(len(num_str)))
if len(num_str) % 2 == 0:
print ("Number of digits is even")
else:
print ("Number of digits is odd")
Converting the input to a string makes sense, because it makes its length easy to determine and helps us with slicing the number up later. Now for the splicing, probably not the most elegant solution, but it works:
if len(num_str) >= 3:
newnum = str(num_str[0:2] + " " + num_str[2:4] + " " + num_str[4:])
print (newnum)
num = int(input('enter the Number you want check: ')
if num > 0 :
for i in range(0,num):
if ( num % 2) == 0:
print('its a even number')
break
else:
print('Its a odd number')
else:
print('its even number')

Python: To check for prime and increment

i have exactly 5 days of practise, an hour daily so kindly forgive if my questions are very low level. No prior coding exp
My objective of the below code is
1- check if entered number is a prime
2- if not print the next biggest prime
def primetest (num): # check if number is a prime
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting an output. Please help
The way you have done has a lot of errors not efficient. By making some modification to your code i have made it much simpler. Read the comments to understand:
def primetest (num): # check if number is a prime
return(all(num % i for i in range(2, num)))
num = int (input ("enter a number:")) # main code:
while True: #loop continues until prime number found(True)
if primetest(num):
print(num,"is a prime number.")
break #(stops loop if prime found)
else: #otherwise repeat by incrementing to the next num until found
print(num,"is not a prime number.")
num += 1
Output:
enter a number:45
45 is not a prime number.
46 is not a prime number.
47 is a prime number.

Categories

Resources