用Python查找empirs,我做错了什么?

2024-03-28 15:27:25 发布

您现在位置:Python中文网/ 问答频道 /正文

An Emirp is a prime number whose reversal is also a prime. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps. Write a program that prints out the first N emirps, five on each line.

Calculate the first N emirp (prime, spelled backwards) numbers, where N is a positive number that the user provides as input.

Implementation Details

You are required to make use of 2 functions (which you must write).

isPrime(value) # Returns true if value is a prime number. reverse (value) # Returns the reverse of the value (i.e. if value is 35, returns 53). You should use these functions in conjunction with logic in your main part of the program, to perform the computation of N emirps and print them out according to the screenshot below.

The general outline for your program would be as follows:

Step 1: Ask user for positive number (input validation) Step 2: Initialize a variable Test to 2 Step 3: While # emirps found is less than the input: Call isPrime with Test, and call it again with reverse(Test). If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then reverse the string. Then turn it back into an int!

我的代码:

n = 0
count = 0
i = 1
def isPrime(value):
    test = 2
    count = 0
    while(test < value):
        if( value % test == 0):
            count+=count
            test+=test
    if(count == 0):
        return 1
    else:
        return 0

def reverse(value):
    reverse = 0
    while(value > 0):
        reverse = reverse * 10 + (value % 10)
        value = value / 10
    return reverse

n = float(input("Please enter a positive number: "))

while(count < n):
    i+=i;
    if(isPrime(i)):
        if(isPrime(reverse(i))):
                print("i" + "\n")
                count+=count
        if((count % (5)) == 0 ):
                print("\n")

错误在哪里?在

已更新代码但仍未运行:

^{pr2}$

Tags: andofthetotestnumberinputif
1条回答
网友
1楼 · 发布于 2024-03-28 15:27:25

你的代码有很多问题。我改变了函数isPrime。这里不需要count,如果你想让test递增1每个循环使用test +=1

def isPrime(value):
test = 2
while(test < value):
    if( value % test != 0):
        test +=1
    else:
        return 0
return 1

有一种简单的方法可以反转数字,方法是将value按相反的顺序生成一个字符串,并将其转换为整数:

^{pr2}$

您必须将输入分配给in在代码中是一个常量5。在任何情况下,您必须将i递增一,如果{}是emirp,则计数增加一:

i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):  
    if(isPrime(i)):
        if(isPrime(reverse(i))):
                print(str(i) + "\n")
                count += 1
                i += 1
        else:
            i += 1
    else:
        i +=1

相关问题 更多 >