close
題目概要:
輸入一個整數,並找出一個數字的所有因數加總等於輸入的整數。如果沒有答案則輸出-1。
解題方向:
從輸入的整數開始找起,一直遞減,直到找到某數因數的總和等於所輸入的整數,或者已經遞減到0。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
import java.util.Vector; | |
import java.util.Iterator; | |
class uva11728{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
int n; | |
int cases=1; | |
while(sc.hasNextInt() && (n=sc.nextInt())!=0){ | |
for(int i=n;i>0;i--){ | |
Vector<Integer> vector=new Vector<Integer>(); | |
int temp=i; | |
//找出某數的因數。 | |
int j=1; | |
while(j<=temp){ | |
if(temp%j==0)vector.add(j); | |
j++; | |
} | |
//因數加總。 | |
Iterator<Integer> iterator=vector.iterator(); | |
int sum=0; | |
while(iterator.hasNext()){ | |
sum=sum+iterator.next(); | |
} | |
//進行判斷。 | |
if(n==sum){ | |
System.out.println("Case "+cases+": "+temp); | |
break; | |
} | |
//當i已經等於1時代表已經沒有答案了,所以輸出-1。 | |
if(i==1)System.out.println("Case "+cases+": -1"); | |
} | |
cases++; | |
} | |
} | |
} |
文章標籤
全站熱搜