2006程式設計競賽第四題
題目:
Factoring a number means representing it as the product of prime numbers.
Please write a program to factoring a number.
程式碼:
import java.util.*; /********************************************* * Factoring a number means representing it as * the product of prime numbers. Please write a * program to factoring a number. *********************************************/ public class E2006_4{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int n = sc.nextInt();//輸入整數 System.out.println("Please input a number: "+ n); List<Integer> list = new ArrayList<Integer>(); prime(list); facNum(list,n); } } public static void prime(List<Integer> list){ /*找前100質數放入容器 */ int i,c=0; for(i=2; i<=100; i++){//質數的定義來寫 for(int j=2; j<=i; j++){ if(i%j==0){ c++; } } if(c==1){ list.add(i);//存取元素至清單 } c = 0; } /*印出 list 存放元素 */ //for(Integer num : list){ System.out.println(num); } //System.out.print(list.size());//容器存放多少個元素 } /*找出相鄰質數相乘 == 輸入的數字 */ public static void facNum(List<Integer> list,int num){ for(int j = 0 ; j < list.size() - 1 ; j ++){ if(list.get(j) * list.get(j + 1) == num){ System.out.println(num+" is product by : "+list.get(j) + "," + list.get(j+1)); break ; } else if(list.get(j) * list.get(j+1) > num){ break ; } } } }Ex.
Please input a number: 221 221 is product by : 13, 17 Please input a number: 77 77 is product by : 7, 11
心得:
list 是朋友教我的,感覺不錯用。困難點是 list 的用法吧!!只能在最近多學。也希望讀者有更好的方式來解答此題,答案給的不足,明確度應該不高ㄅQQ
留言
張貼留言