寻找List之和的最近素数

简介: 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 .

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 should equal the closest prime number .


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 equal the closest prime number (7) .

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!
    }
}

 

将编程看作是一门艺术,而不单单是个技术。 敲打的英文字符是我的黑白琴键, 思维图纸画出的是我编写的五线谱。 当美妙的华章响起,现实通往二进制的大门即将被打开。
相关文章
|
人工智能
二分思想判断数组中是否有两数和为sum
1 /* 2 一个N个整数的无序数组,给你一个数sum,求出数组中是否存在两个数,使他们的和为sum O(nlogn) 3 解题思路:先排序 在左右夹击判断,类似二分查找的思想。 4 */ 5 #include 6 #include 7 int find(int ...
758 0
LeetCode 167:两数之和 II - 输入有序数组 Two Sum II - Input array is sorted
公众号: 爱写bug(ID:icodebugs) 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
988 0

热门文章

最新文章