简体   繁体   English

数字1 - 1000的素数测试

[英]Prime number test for numbers 1 - 1000

As a homework I have to write a prime number test, that gives back a "true" or "false" statement. 作为一个家庭作业,我必须写一个素数测试,这会给出一个“真实”或“虚假”的陈述。 The tricky thing is, I have to write a csv.-file that includes the "true" and "false" statements for the numbers 1 to 1000. I used this code for the prime number test 棘手的是,我必须编写一个csv.-文件,其中包含数字1到1000的“true”和“false”语句。我使用此代码进行素数测试

def Primzahl(n):
if n < 2:
    return False
if n == 2: 
    return True    
if not n & 1: 
    return False
for x in range(3, int(n**0.5) + 1, 2):
    if n % x == 0:
        return False
return True

and

for i in range (1,1001):
    Primzahl (i)
    print (i)

My for-loop only gives out the numbers 1,1000 but not the true or false statements. 我的for-loop只给出数字1,1000而不是真或假的陈述。 Do I have to include if and else in my for loop? 我是否必须在for循环中包含if和else? Can anyone help? 有人可以帮忙吗?

The problem is print(i) . 问题是print(i) That will write i , which is the number from your range call. 这将写出i ,这是你的range调用中的数字。 You will also need to print the value returned by your function, eg print(Primzahl(i)) . 您还需要打印函数返回的值,例如print(Primzahl(i))

Currently you're only printing i, and not the return value from your method. 目前您只打印i,而不是方法的返回值。 You aren't doing anything with the return value from your method. 您没有使用方法的返回值执行任何操作。 You should assign the result to a variable and print the variable also. 您应该将结果分配给变量并同时打印变量。 (You could also just call the method from within the print statement.) (您也可以从print语句中调用该方法。)

for i in range (1,1001):
isPrime = Primzahl(i)
print (i + ": " + isPrime)

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

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