以下是我的Java代码,用于打印'n'质数,但我想对其进行修改,以便可以以相反的顺序打印备用质数。
import java.util.Scanner;
class PrimeNumberDemo
{
public static void main(String args[])
{
int n;
int status = 1;
int num = 3;
//For capturing the value of n
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
//The entered value is stored in the var n
n = scanner.nextInt();
if (n >= 1)
{
System.out.println("First "+n+" prime numbers are:");
//2 is a known prime number
System.out.println(2);
}
for ( int i = 2 ; i <=n ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
i++;
}
status = 1;
num++;
}
}
}
根据您的代码,我做了一些修改,以下是我如何以相反的顺序获得备用素数
public static void main(String args[])
{
int n;
int status = 1;
int num = 3;
List<Integer> primeNumberList=new ArrayList<Integer>();
//For capturing the value of n
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
//The entered value is stored in the var n
n = scanner.nextInt();
if (n >= 1)
{
System.out.println("First "+n+" prime numbers are:");
//2 is a known prime number
System.out.println(2);
primeNumberList.add(2);
}
for ( int i = 2 ; i <=n ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
primeNumberList.add(num);
i++;
}
status = 1;
num++;
}
//reversing collection
Collections.reverse(primeNumberList);
System.out.println("\n");
System.out.println("Alternate Prime numbers in reverse order \n");
for(int k=0;k<primeNumberList.size();k++){
if((k%2)==0)
System.out.println(""+primeNumberList.get(k));
}
}
结果输出
Enter the value of n:
10
First 10 prime numbers are:
2
3
5
7
11
13
17
19
23
29
Alternate Prime numbers in reverse order
29
19
13
7
3
您可以在ArrayList<Integer>
中添加每个数字
设置所有值后,只需反转列表即可。
Collections.reverse(list);
我会这样做。
import java.util.Scanner;
class AlternatePrimeNumbers
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Main obj = new Main();
System.out.print("Enter the value of n :- ");
int num = input.nextInt();
System.out.println("Alternate Prime numbers in reverse order upto "+num+" :- ");
obj.alternatePrimeNumbers(num);
}
}
class Main
{
public void alternatePrimeNumbers(int n)
{
int i;
boolean prime,flag=true;
for(i=n; i>=1; i--)
{
prime = checkPrime(i);
if(prime)
{
if(flag)
{
System.out.print(i+" ");
flag = false;
}
else if(flag==false)
flag = true;
}
}
}
public boolean checkPrime(int n)
{
int i;
boolean prime=true;
for(i=2; i<=n/2; i++)
{
if(n%i==0) //condition for non-prime numbers
{
prime = false;
break;
}
}
return prime;
}
}