ในการค้นหาผลคูณของตัวประกอบเฉพาะของตัวเลข โค้ด Java มีดังต่อไปนี้ −
ตัวอย่าง
public class Demo {
public static long prime_factors(int num){
long my_prod = 1;
for (int i = 2; i <= num; i++){
if (num % i == 0){
boolean is_prime = true;
for (int j = 2; j <= i / 2; j++){
if (i % j == 0){
is_prime = false;
break;
}
}
if (is_prime){
my_prod = my_prod * i;
}
}
}
return my_prod;
}
public static void main(String[] args){
int num = 68;
System.out.println("The product of unique prime factors is ");
System.out.print(prime_factors(num));
}
} ผลลัพธ์
The product of unique prime factors is 34
คลาสที่ชื่อว่า Demo มีฟังก์ชันสแตติกชื่อ 'prime_factors' ซึ่งจะค้นหาตัวประกอบเฉพาะของตัวเลข ค้นหาจำนวนเฉพาะ และเก็บผลคูณของปัจจัยเฉพาะเหล่านี้ไว้ในตัวแปร ในฟังก์ชันหลัก ค่าของตัวเลขถูกกำหนด และฟังก์ชันถูกเรียกใช้โดยส่งตัวเลขเป็นพารามิเตอร์ ข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล