Java程式:顯示1到N之間的所有素數
在本文中,我們將學習如何在Java中顯示1到N之間的所有素數。從1到無窮大的所有正數稱為自然數。素數是隻有兩個因數1和自身,並且不能被任何其他數字整除的特殊數字。
如果一個數的唯一因數只有1和自身,則它是一個素數。11是一個素數。它的因數是1和11本身。一些素數的例子是2、3、5、7、11、13等等。2是唯一的一個偶數素數。所有其他的素數都是奇數。
以下是相同的演示 -
輸入
假設我們的輸入是 -
Enter the value of n :10
輸出
期望的輸出將是 -
2 3 5 7
演算法
Step1- Start Step 2- Declare an integer : n Step 3- Prompt the user to enter an integer value/ Hardcode the integer Step 4- Read the values Step 5- Using a while loop from 1 to n, check if the 'i' value is divisible by any number from 2 to i. Step 6- If yes, check the next number Step 7- If no, store the number as a prime number Step 8- Display the 'i' value as LCM of the two numbers Step 9- Stop
示例1
在這裡,輸入是根據提示由使用者輸入的。您可以在我們的程式碼執行工具 中即時嘗試此示例。
import java.util.Scanner; public class PrimeNumbers{ public static void main(String arg[]){ int i,n,counter, j; Scanner scanner = new Scanner(System.in); System.out.println("Required packages have been imported"); System.out.println("A reader object has been defined "); System.out.print("Enter the n value : "); n=scanner.nextInt(); System.out.print("Prime numbers between 1 to 10 are "); for(j=2;j<=n;j++){ counter=0; for(i=1;i<=j;i++){ if(j%i==0){ counter++; } } if(counter==2) System.out.print(j+" "); } } }
輸出
Required packages have been imported A reader object has been defined Enter the n value : 10 Prime numbers between 1 to 10 are 2 3 5 7
示例2
這裡,整數已預先定義,其值在控制檯上被訪問和顯示。
public class PrimeNumbers{ public static void main(String arg[]){ int i,n,counter, j; n= 10; System.out.printf("Enter the n value is %d ", n); System.out.printf("\nPrime numbers between 1 to %d are ", n); for(j=2;j<=n;j++){ counter=0; for(i=1;i<=j;i++){ if(j%i==0){ counter++; } } if(counter==2) System.out.print(j+" "); } } }
輸出
Enter the n value is 10 Prime numbers between 1 to 10 are 2 3 5 7
廣告