java/python 输出n以内的所有素数(练习)

Java

import java.util.Scanner;
public class prime{

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入是一个大于1的整数:")
        int n;
        n = in.nextInt();
        for(int i=2; i<=n; i+=2){
            int isprime;
            isprime = 1;
            for(int k=2; k<i/2+1; k+=2){
                if(i%k==0){
                    isprime = 0;
                    break;
                }
            }
        if(isprime == 1){
            System.out.print(i+" ");
        }
        }
    }
}

python

n = int(input("请输入一个大于1的整数:"))
for i in range(2,n+1,2):
    isprime = 1
    for k in range(2,int(i/2)+1,2):
        if i%k == 0:
            isprime = 0
            break
    if isprime:
        print(i, end = " ")

That’s all.

你可能感兴趣的:(python,java)