尋找List之和的最近素數
阿新 • • 發佈:2018-07-29
sum ask list 進入 ron class tran -c element
Task :
Given a List [] of n integers , find minimum mumber to be inserted in a list, so that sum of all elements of list should equal the closest prime number .
Notes
-
List size is at least 2 .
-
List‘s numbers will only positives (n > 0) .
-
Repeatition of numbers in the list could occur .
-
The newer list‘s sum
Input >> Output Examples
1- minimumNumber ({3,1,2}) ==> return (1)
Explanation:
- Since , the sum of the list‘s elements equal to (6) , the minimum number to be inserted to transform the sum to prime number is (1) , which will make the sum of the List
2- minimumNumber ({2,12,8,4,6}) ==> return (5)
Explanation:
- Since , the sum of the list‘s elements equal to (32) , the minimum number to be inserted to transform the sum to prime number is (5) , which will make the sum of the List equal the closest prime number (37)
3- minimumNumber ({50,39,49,6,17,28}) ==> return (2)
Explanation:
- Since , the sum of the list‘s elements equal to (189) , the minimum number to be inserted to transform the sum to prime number is (2) , which will make the sum of the List equal the closest prime number (191) .
public class Solution { public static int minimumNumber(int[] numbers) { //首先求得現在list中的數值之和 int sumOri = 0; for(int i=0;i<numbers.length;i++){ sumOri += numbers[i]; } //用另一個數對原始和進行遞增 int sumNow = sumOri; boolean searchPrime = true; //do...while遞增原始數值,並判定是否為素數 while(searchPrime) { int count = 0; for(int i=2;i<=Math.floor(sumNow/2);i++){ if(sumNow%i==0){ //合數進入 count++; } } //count為0,這個數是質數,停止查找 if(count == 0){ searchPrime = false; }else{ //遞增新的和 sumNow++; } } return sumNow-sumOri; // Do your magic! } }
尋找List之和的最近素數