Finding 'k' such that its modulus with each array element is same
Last Updated :
12 Dec, 2024
Given an array of n integers .We need to find all 'k' such that
arr[0] % k = arr[1] % k = ....... = arr[n-1] % k
Examples:
Input : arr[] = {6, 38, 34}
Output : 1 2 4
6%1 = 38%1 = 34%1 = 0
6%2 = 38%2 = 34%2 = 0
6%4 = 38%4 = 34%2 = 2
Input : arr[] = {3, 2}
Output : 1
Suppose the array contains only two elements a and b (b>a). So we can write b = a + d where d is a positive integer and 'k' be a number such that b%k = a%k.
(a + d)%k = a%k
a%k + d%k = a%k
d%k = 0
Now what we get from the above calculation is that 'k' should be a divisor of difference between the two numbers.
Now what we have to do when we have an array of integers
- Find out the absolute difference 'd' between maximum and minimum element of the array
- Find out all the divisors of 'd'
- Step 3: For each divisor check if arr[i]%divisor(d) is same or not .if it is same print it.
Implementation:
C++
// C++ implementation of finding all k
// such that arr[i]%k is same for each i
#include<bits/stdc++.h>
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 <int> v;
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<v.size(); 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<n; 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;
}
Java
// Java implementation of finding all k
// such that arr[i]%k is same for each i
import java.util.Arrays;
import java.util.Vector;
class Test
{
// Prints all k such that arr[i]%k is same for all i
static void printEqualModNumbers (int arr[], int n)
{
// sort the numbers
Arrays.sort(arr);
// 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){
System.out.println("Infinite solution");
return;
}
// Find all divisors of d and store in
// a vector v[]
Vector<Integer> v = new Vector<>();
for (int i=1; i*i<=d; i++)
{
if (d%i == 0)
{
v.add(i);
if (i != d/i)
v.add(d/i);
}
}
// check for each v[i] if its modulus with
// each array element is same or not
for (int i=0; i<v.size(); i++)
{
int temp = arr[0]%v.get(i);
// checking for each array element if
// its modulus with k is equal to k or not
int j;
for (j=1; j<n; j++)
if (arr[j] % v.get(i) != temp)
break;
// if check is true print v[i]
if (j == n)
System.out.print(v.get(i) + " ");
}
}
// Driver method
public static void main(String args[])
{
int arr[] = {38, 6, 34};
printEqualModNumbers(arr, arr.length);
}
}
Python3
# Python3 implementation of finding all k
# such that arr[i]%k is same for each i
# Prints all k such that arr[i]%k is
# same for all i
def printEqualModNumbers(arr, n):
# sort the numbers
arr.sort();
# max difference will be the difference
# between first and last element of
# sorted array
d = arr[n - 1] - arr[0];
// Case when all the array elements are same
if(d==0):
print("Infinite solution")
return
# Find all divisors of d and store
# in a vector v[]
v = [];
i = 1;
while (i * i <= d):
if (d % i == 0):
v.append(i);
if (i != d / i):
v.append(d / i);
i += 1;
# check for each v[i] if its modulus with
# each array element is same or not
for i in range(len(v)):
temp = arr[0] % v[i];
# checking for each array element if
# its modulus with k is equal to k or not
j = 1;
while (j < n):
if (arr[j] % v[i] != temp):
break;
j += 1;
# if check is true print v[i]
if (j == n):
print(v[i], end = " ");
# Driver Code
arr = [38, 6, 34];
printEqualModNumbers(arr, len(arr));
# This code is contributed by mits
C#
// C# implementation of finding all k
// such that arr[i]%k is same for each i
using System;
using System.Collections;
class Test
{
// Prints all k such that arr[i]%k is same for all i
static void printEqualModNumbers (int []arr, int n)
{
// sort the numbers
Array.Sort(arr);
// 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){
Console.write("Infinite solution");
return;
}
// Find all divisors of d and store in
// a vector v[]
ArrayList v = new ArrayList();
for (int i=1; i*i<=d; i++)
{
if (d%i == 0)
{
v.Add(i);
if (i != d/i)
v.Add(d/i);
}
}
// check for each v[i] if its modulus with
// each array element is same or not
for (int i=0; i<v.Count; i++)
{
int temp = arr[0]%(int)v[i];
// checking for each array element if
// its modulus with k is equal to k or not
int j;
for (j=1; j<n; j++)
if (arr[j] % (int)v[i] != temp)
break;
// if check is true print v[i]
if (j == n)
Console.Write(v[i] + " ");
}
}
// Driver method
public static void Main()
{
int []arr = {38, 6, 34};
printEqualModNumbers(arr, arr.Length);
}
}
// This code is contributed by mits
JavaScript
<script>
// JavaScript implementation of finding all k
// such that arr[i]%k is same for each i
// Prints all k such that arr[i]%k is same for all i
function printEqualModNumbers (arr, n)
{
// sort the numbers
arr.sort((a, b) => a - b);
// max difference will be the difference between
// first and last element of sorted array
d = arr[n-1] - arr[0];
// Case when all the array elements are same
if(d==0){
document.write("Infinite solution");
return;
}
// Find all divisors of d and store in
// a vector v[]
v = new Array();
for (i=1; i*i<=d; i++)
{
if (d%i == 0)
{
v.push(i);
if (i != d/i)
v.push(d/i);
}
}
// check for each v[i] if its modulus with
// each array element is same or not
for (i=0; i< v.length; i++)
{
temp = arr[0]%v[i];
// checking for each array element if
// its modulus with k is equal to k or not
j=1;
for (; j<n; j++)
if (arr[j] % v[i] != temp)
break;
// if check is true print v[i]
if (j == n)
document.write(v[i] + " ");
}
}
// Driver method
let arr = new Array(38, 6, 34);
printEqualModNumbers(arr, arr.length);
// This code is contributed by _saurabh_jaiswal
</script>
PHP
<?php
// PHP implementation of finding all k
// such that arr[i]%k is same for each i
// Prints all k such that arr[i]%k is same for all i
function printEqualModNumbers ($arr, $n)
{
// sort the numbers
sort($arr);
// max difference will be the difference between
// first and last element of sorted array
$d = $arr[$n-1] - $arr[0];
// Case when all the array elements are same
if(d==0){
print("Infinite solution");
return;
}
// Find all divisors of d and store in
// a vector v[]
$v = array();
for ($i=1; $i*$i<=$d; $i++)
{
if ($d%$i == 0)
{
array_push($v,$i);
if ($i != $d/$i)
array_push($v,$d/$i);
}
}
// check for each v[i] if its modulus with
// each array element is same or not
for ($i=0; $i<count($v); $i++)
{
$temp = $arr[0]%$v[$i];
// checking for each array element if
// its modulus with k is equal to k or not
$j=1;
for (; $j<$n; $j++)
if ($arr[$j] % $v[$i] != $temp)
break;
// if check is true print v[i]
if ($j == $n)
print($v[$i]." ");
}
}
// Driver method
$arr = array(38, 6, 34);
printEqualModNumbers($arr, count($arr));
// This code is contributed by mits
?>
Time Complexity: O(nlog(n))
Since the given array has to be sorted for the given problem, we use the sorting algorithm which takes O(nlog(n)) time.
Space Complexity: O(n)
We use a vector to store all the divisors of the difference of the first and the last element of the sorted array. This has a space complexity of O(n).
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read