简体   繁体   中英

Test if each digit of a number is prime or not

I want to test if each digit in a number entered by the user is prime or not. For example: For a number entered like 124: 1 is a prime number 2 is a prime number 4 is a composite number

I have done as follows but clearly there is an error in this.

x=int(input("Enter the number you want to check\n"))
primeflag=True
lst=[]
prime=[]
com=[]
while x>0:
    y=x%10
    x=x//10
    lst.append(y)

l=(len(lst))
for i in (0,l-1):
    for j in range(2,lst[i]-1):
        if lst[i]%j==0:
            primeflag=False
        else:
            primeflag=True
    if primeflag==True:
        prime.append(lst[i])
    else:
        com.append(lst[i])
print(prime,"are Prime Numbers")
print(com,"are Composite Numbers")

Not at the best way to do it . Will remove after a while but might help to debug your issue. There were many errors (logical) one so I thought it might give you a push. There can be more I have not tested this myself and will remove after a while. Have a look I have modified your code only.

x=list(input("Enter the number you want to check\n"))
primeflag=True
lst=[]
prime=[]
com=[]
lst=list(map(int,x))
l=(len(lst))
for i in range(0,l):
    primeflag=False
    print(lst[i])
    if(lst[i]==2 ):
        prime.append(lst[i])
        continue
    for j in range(2,lst[i]+1):
        if lst[i]%j==0:
            primeflag=False
        else:
            primeflag=True
    if primeflag:
        prime.append(lst[i])
    else:
        com.append(lst[i])
print(prime,"are Prime Numbers")
print(com,"are Composite Numbers")

Wrap in a function or something and call it while iterating over the list. but frankly you can just define a dict for 0-9 numbers with status prime or not. It will be more efficient

There are multiple problems with this loop:

for j in range(2,lst[i]-1):
    if lst[i]%j==0:
        primeflag=False
    else:
        primeflag=True

The first problem is that you replace primeflag over and over, so ultimately this is just testing whether the last value that you checked was a divisor or not. What you want to check is whether any of the values was a divisor. So, you need to start off with True before the loop, and never set it back to True if you've ever set it to False :

primeflag=True
for j in range(2,lst[i]-1):
    if lst[i]%j==0:
        primeflag=False

While we're at it, once you find a factor, you can break , because you already know the number is composite:

primeflag=True
for j in range(2,lst[i]-1):
    if lst[i]%j==0:
        primeflag=False
        break

The second problem is that range(2,lst[i]-1) is all of the numbers up to but not including lst[i]-1 . Ranges are half-open in Python. So:

primeflag=True
for j in range(2, lst[i]):
    if lst[i]%j==0:
        primeflag=False
        break

This one, despite being wrong, doesn't actually break anything. Why? Well, you actually only need to test up to sqrt(lst[i])) , and you're already getting 0, 1, and 2 wrong because of a different bug, and for every larger number, n-1 > sqrt(n) , so it doesn't matter that you miss n-1 .

However, your outer loop has the same problem:

for i in (0,l-1):

… and there, it is a problem—you never check the last digit.


The third problem is that, for the digits 0, 1, and 2, range(2, lst[i]) is empty, so you're not going to loop at all. For your original code, that means you're just going to use the leftover value of primeflag from the last digit. With the fixes above, it means you're going to assume all three of those are prime, which is right for 1 (by your definition) and 2, but not for 0. The simplest fix is:

primeflag = lst[i] != 0
for j in range(2, lst[i]):
    if lst[i]%j==0:
        primeflag=False
        break

But really, once we've implicitly put in hardcoded answers for 0, 1, and 2, why not (a) make it explicit, and (b) put in the answers for all 10 digits? Then you can just skip the whole loop, and you won't have all of these opportunities to get things wrong in the first place:

primeflag = lst[i] in {1, 2, 3, 5, 7}

Finally, you can simplify the loop by just looping over the digits directly, instead of looping over a range up to the length of the list of digits—which again makes things simpler, and removes one of the opportunities for error (the one that caused you to miss the last digit):

for digit in lst:
    if digit in {1, 2, 3, 5, 7}:
        prime.append(digit)
    else:
        com.append(digit)

One last thing: your code generates the digits in reverse order (so, eg, input 124 gives you [4, 2, 1] ), but your intended output seems to be the digits in forward order ("1 is a prime number 2 is a prime number 4 is a composite number"), so you may want to loop over lst[::-1] .

Putting it all together, and cleaning things up a bit to fit PEP 8 style :

x = int(input("Enter the number you want to check\n"))
lst = []
while x:
    y = x%10
    x = x//10
    lst.append(y)

prime, com = [], []
for digit in lst[::-1]:
    if digit in {1, 2, 3, 5, 7}:
        prime.append(digit)
    else:
        com.append(digit)

print(prime, "are Prime Numbers")
print(com, "are Composite Numbers")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM