简体   繁体   English

测试一个数的每一位是否都是质数

[英]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例如:对于像 124 这样输入的数字:1 是质数 2 是质数 4 是合数

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.但坦率地说,您可以为 0-9 数字定义一个 dict 是否具有状态素数。 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.第一个问题是你primeflag遍地替换primeflag ,所以最终这只是测试你检查的最后一个值是否是除数。 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 :因此,您需要在循环之前以True开始,并且如果您曾经将其设置为False ,则永远不要将其设置回True

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:当我们在做的时候,一旦你找到一个因子,你就可以break ,因为你已经知道这个数字是合数:

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 .第二个问题是range(2,lst[i]-1)是所有数字,但不包括lst[i]-1 Ranges are half-open in Python.范围在 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 .好吧,您实际上只需要测试sqrt(lst[i])) ,并且由于不同的错误,您已经得到 0、1 和 2 错误,并且对于每个更大的数字, n-1 > sqrt(n) ,所以你错过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.第三个问题是,对于数字 0、1 和 2, range(2, lst[i])是空的,所以你根本不会循环。 For your original code, that means you're just going to use the leftover value of primeflag from the last digit.对于您的原始代码,这意味着您将只使用最后一位数的primeflag的剩余值。 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:通过上面的修复,这意味着您将假设所有这三个都是素数,这适用于 1(根据您的定义)和 2,但不适用于 0。最简单的修复是:

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?但实际上,一旦我们隐含地输入了 0、1 和 2 的硬编码答案,为什么不 (a) 明确表示,以及 (b) 输入所有 10 位数字的答案? 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] .最后一件事:您的代码以相反的顺序生成数字(例如,输入124为您提供[4, 2, 1] ),但您的预期输出似乎是按正向顺序排列的数字(“1 是质数 2是质数 4 是合数”),因此您可能需要遍历lst[::-1]

Putting it all together, and cleaning things up a bit to fit PEP 8 style :把它们放在一起,稍微整理一下以适应PEP 8 风格

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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