This question already has answers here:
How to create the most compact mapping n → isprime(n) up to a limit N?
(29 answers)
Closed last month.
input a integer X and tell if it is a prime.
If it is a prime, output 'Y'
If not, output 'N' and the smallest prime factor.
Here is the program I have tried to write.
X = int(input('enter a integer X:'))
for i in range(2, X):
if X % i == 0:
print('Y')
else:
print('N')
But I would like to print just one time 'Y' or 'N'. And I also do not know how to make the smallest prime factor show on my program result.
Thank you all for helping me
Use any and := walrus operator along with generator like this
This will work for python >= 3.8.
n = int(input("Enter a number : "))
j = 2
if any(((k:=j) and (not n%j)) for j in range(2, int(n**0.5)+1)) :
print(k)
else:
print("prime")
n = int(input("Enter Number:")) # input from user
# ====================================PRIME CHECK==================================== #
flag = 0
for i in range(2,n): # looping to check if number is divisible by other numbers
if n % i == 0:
flag = 1 # setting flag value to 1
print(i) # printing value of i for which n is divisible
break # to exit from the if clause
if flag == 1: # checking if the value of flag is 1 then print it is not prime
print(n, "is not a Prime")
else: # else print prime and the value of n
print(n, "is Prime")
Related
Trying to write a program that checks if a number is prime.
Wrote the below code, but do not understand why do I have an output of 2 lines:
num = int(input("Provide number to check if prime: "))
if num <=1:
print("Invalid choice, try again")
num = int(input("Provide number to check if prime: "))
for i in range(2,num):
if num% i ==0:
print("Number is not prime")
break
if num %i !=0:
print("Number is prime")
My output is :
Provide number to check if prime: 15
Number is prime
Number is not prime
The sympy.isprime() is a built-in function under the SymPy module and can be utilized for checking of possible prime numbers. It is a direct function and returns True if the number to be checked is prime and False if the number is not prime.
>>> import simpy
>>> sympy.isprime(8)
False
>>> sympy.isprime(11)
True
or else define a function like this
>>> def isPrime(k):
# 1 is not prime number
if k==1:
return False
# 2, 3 are prime
if k==2 or k==3:
return True
# even numbers are not prime
if k%2==0:
return False
# check all numbers till square root of the number ,
# if the division results in remainder 0
# (skip 2 since we dont want to divide by even numbers)
for i in range(3, int(k**0.5)+1, 2):
if k%i==0:
return False
return True
>>> print(isPrime(13))
True
>>> print(isPrime(18))
False
As the first thing, you should remember that 1 isn't a prime number by definition, even if it can't be divided by any other number:
if (num == 1):
print("The number is NOT prime")
else:
for i in range(2, num):
if (num%i == 0): # If the number has a divisor
print("The number is NOT prime")
break
else: # If the for loop ends without reaching any break
print("The number IS prime")
The else branch of a for loop is reached when the loop ends without reaching any break AND the loop executes at least one time.
To better understand my answer, I would suggest to read this.
The error with your solution is caused by the loop printing that the number is prime for each time num%i == 0, so taking num = 6:
6%4 != 0 # The number is prime
6%5 != 0 # The number is prime
As Rajarshi Ghosh suggested, you should know that while programming it's a good idea to use imported functions to do this simple operations, in order to avoid long operations for such a simple job.
If you don't want to use an imported function, I would suggest you to read this article where they explained 6 ways of finding if a number is prime without using functions made by others.
You have issues in output, not only for the case of 15, but also for cases smaller than 1. The following code should work. It has two improvements.
It prints the correct output for 15. The key is to move the else block to align with the for loop.
It prints the correct output for any number smaller than 1, which is not prime. The key is to use the while-break method to get user enter right number until it is bigger than 1.
num = int(input("Provide number to check if prime: "))
while num <=1: #you need to use while loop
print("Invalid choice, try again")
num = int(input("Provide number to check if prime: "))
if num > 1: #only evaluate number is prime or not if it is greater than 1
for i in range(2,num):
if num% i ==0:
print("Number is not prime")
break
else: #to move the `else` block to align with the `for` loop.
print("Number is prime")
break #add a break here
Output:
What is a while loop?
A while loop tests the input condition. Every time the loop finishes, the condition is reevaluated (only evaluate number is prime or not if it is greater than 1). As long as the the number entered is <=1, the loop keeps executing (keep asking users for input).
If you want to just check whether a number is prime or not just do the following:
num = int(input("Provide number to check if prime: "))
flagNotPrime = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flagNotPrime = True
break
if flagNotPrime:
print("Number is not prime")
else:
print("Number is prime")
Firstly, numbers that are <= 1 are not prime numbers. Therefore, the above code only proceeds if the num is greater than 1.
Secondly, the code checks if num is exactly divisible by any number from 2 to num - 1. If there is a factor in that range, the number is not prime, so the flag is set to True and the loop is broken using break.
Lastly, outside the loop, if the flag is True then num is not prime.
def prime_no():
number = int(input("Enter your number for which you wanna generate prime factors: "))
prime = [2,3]
numb = [*range(4, number + 1)]
for x in numb:
while x > number:
if x % 2 == 0:
continue
if x % numb == 0 and x != numb:
continue
else:
prime.append(x)
print(prime)
Second is something different in while loop because stack was recognizing it as error.
The output remains the same [2,3]. What I am doing wrong?
numb is a list and the modulo operator doesn't work with a list. You're also not indenting properly. As well, x is a number and you're checking if it doesn't equal the list numb which it will never equal. Hence it's always continuing .
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
n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)
This question already has answers here:
To find first N prime numbers in python
(30 answers)
Closed 5 years ago.
I’m new to python and I’m trying to figure out how to make a function where you enter a number and it gives you the number prime.
Example: If I enter 6 it returns 13. Since 13 is the 6th prime.
Preferably no modules except ones in standard library,
Thank you
This is what you are looking for:
def nth_prime_number(n):
# initial prime number list
prime_list = [2]
# first number to test if prime
num = 3
# keep generating primes until we get to the nth one
while len(prime_list) < n:
# check if num is divisible by any prime before it
for p in prime_list:
# if there is no remainder dividing the number
# then the number is not a prime
if num % p == 0:
# break to stop testing more numbers, we know it's not a prime
break
# if it is a prime, then add it to the list
# after a for loop, else runs if the "break" command has not been given
else:
# append to prime list
prime_list.append(num)
# same optimization you had, don't check even numbers
num += 2
# return the last prime number generated
return prime_list[-1]
x = nth_prime_number(8)
print(x)
Try this code !
I am also attach the screenshot of the output .
num=int(input("Enter Position : "))
r =1000
count=0
import sys
for a in range(2,sys.maxsize**10):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
count=count+1
if(count==num):
print("Prime Number at position " , num , " is " , a)
break