InterviewSolution
| 1. |
Write a Java program to store the modulus of every element of array A [ ] with 7 in array B[ ]. Print the elements of array B[ ]. Also display the sum of those elements divisible by 7. (Array A [ ] consists of 5 elements).Sample input - 35 53 70 40 14 Output - 0 4 0 5 0Sum of elements divisible by 7 : 119 |
|
Answer» Answer: Step by step DESCRIPTIVE logic to count duplicate elements in array. Input size and elements in array from user. ... Initialize another VARIABLE count with 0 to store duplicate count. To count total duplicate elements in given array we NEED two loops. ... Run another inner loop to find first duplicate of current array element. Explanation: // C++ implementation of finding all k // such that arr[i]%k is same for each i #include using namespace std;
// Prints all k such that arr[i]%k is same for all i void printEqualModNumbers (int arr[], int n) { // sort the numbers sort(arr, arr + n);
// max difference will be the difference between // first and LAST element of sorted array int d = arr[n-1] - arr[0];
// CASE when all the array elements are same if(d==0){ cout<<"Infinite solution"; return; }
// Find all divisors of d and store in // a vector v[] vector for (int i=1; i*i<=d; i++) { if (d%i == 0) { v.push_back(i); if (i != d/i) v.push_back(d/i); } }
// check for each v[i] if its modulus with // each array element is same or not for (int i=0; i { int temp = arr[0]%v[i]; // checking for each array element if // its modulus with k is equal to k or not int j; for (j=1; j if (arr[j] % v[i] != temp) break; // if check is true print v[i] if (j == n) cout << v[i] <<" "; } } // Driver function int main() { int arr[] = {38, 6, 34}; int n = sizeof(arr)/sizeof(arr[0]); printEqualModNumbers(arr, n); return 0; } |
|