📌  相关文章
📜  使所有数组元素可被数字K整除

📅  最后修改于: 2021-04-22 00:41:05             🧑  作者: Mango

给定一个数组arr []和一个数字K ,任务是使数组的所有元素可被K整除。要使元素被K整除,可以执行以下操作:

  • 选择数组中的任何索引C。
  • 您可以从任何数字中减去任何值直到索引C,并且可以将任何值添加到索引C之后的任何元素中。
  • 上述操作所需的唯一条件是可以将减去索引C的值的总和添加到索引C之后的元素中。

将索引C的值和减去的数字的差打印到在索引C之后添加的数字。

例子:

解释:

方法:

  • 创建两个辅助数组arr1 []和arr2 []。
  • 第一个数组arr1 []存储可以从每个元素中减去的元素的值,以使其在arr []中被K整除。
  • 第二个数组arr2 []存储可以添加的元素的值,以使该元素可以被K整除。
  • 然后迭代C的可能值,并找到索引,其中从arr1 []减去该索引的值之和等于或大于等于arr2 []中C之后的索引的相加值之和。

下面是上述方法的实现:

C++
// C++ implementation to make
// the array elements divisible by K
#include 
using namespace std;
  
// Function to make array divisible
pair makeDivisble(int arr[], int n, int k)
{
      
    vectorb1; 
    vectorb2;
    int c, suml, sumr, index, rem;
      
    // For each element of array
    // how much number to be subtracted
    // to make it divisible by k 
    for (int i = 0; i < n; i++)
        b1.push_back(arr[i] % k);
      
    // For each element of array
    // how much number to be added
    // to make it divisible by K 
    for (int j = 0; j < n; j++)
        if ((arr[j] % k) != 0)
            b2.push_back(k - (arr[j] % k));
        else
            b2.push_back(0);
              
    c = 0;
    float mini = INT_MAX;
    suml = 0;
    sumr = 0;
    index = -1;
      
    // Calculate minimum difference 
    for (int c = 0; c < n; c++)
    {
        suml = accumulate(b1.begin(),b1.begin() + c + 1, 0);
        sumr = accumulate(b2.begin() + c + 1 , b2.end(), 0);
        if (suml >= sumr)
        {
            rem = suml - sumr;
            if (rem < mini)
            {
                mini = rem;
                index = c;
            }
        }
    }
      
    return make_pair(index, mini);
  
}
  
// Driver Code
int main() {
    int arr[] = {1, 14, 4, 41, 1};
    int k = 7;
    int n=sizeof(arr)/sizeof(arr[0]);
      
    pairans;
    ans = makeDivisble(arr, n, k);
    cout << ans.first << " " << ans.second;
      
    return 0;
}
  
// This code is contributed by Atul_kumar_Shrivastava


Python
# Python implementation to make
# the array elements divisible by K
  
# Function to make array divisible
def makeDivisble(arr, k):
    n = len(arr)
    b1 =[]
    b2 =[]
      
    # For each element of array
    # how much number to be subtracted
    # to make it divisible by k 
    for i in range (n):
        b1.append(arr[i]% k)
      
    # For each element of array
    # how much number to be added
    # to make it divisible by K 
    for j in range(n):
        if ((arr[j]% k)!= 0):
            b2.append(k-(arr[j]% k))
        else:
            b2.append(0) 
    c = 0
    mini = float('inf')
    suml = 0
    sumr = 0
    index = -1
      
    # Calculate minimum difference 
    for c in range(0, n+1, 1):
        suml = sum(b1[ : c + 1])
        sumr = sum(b2)
        if suml>= sumr:
            rem = suml-sumr
            if rem


输出:
3 5