ในบทความนี้ เราจะเข้าใจวิธีการแสดงจำนวนเฉพาะทั้งหมดตั้งแต่ 1 ถึง N ใน Java จำนวนบวกที่เป็นไปได้ทั้งหมดตั้งแต่ 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