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}$
你的代码有很多问题。我改变了函数
isPrime
。这里不需要count
,如果你想让test
递增1
每个循环使用test +=1
:有一种简单的方法可以反转数字,方法是将
^{pr2}$value
按相反的顺序生成一个字符串,并将其转换为整数:您必须将输入分配给}是emirp,则计数增加一:
i
。n
在代码中是一个常量5
。在任何情况下,您必须将i
递增一,如果{相关问题 更多 >
编程相关推荐