-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivisible Sum Pairs.php
More file actions
51 lines (38 loc) · 995 Bytes
/
Divisible Sum Pairs.php
File metadata and controls
51 lines (38 loc) · 995 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/*
PROBLEM:
Given an array of integers and a positive integer k, determine the number of (i,j) pairs where i < j and ar[i] + ar[j] is
divisible by k.
Example
ar = [1, 2, 3, 4, 5, 6];
k = 5;
Three pairs meet the criteria: [1, 4], [2, 3], and [4, 6].
Function Description
Complete the divisibleSumPairs function in the editor below.
divisibleSumPairs has the following parameter(s):
- int n: the length of array
- int ar[n]: an array of integers
- int k: the integer divisor
Returns
- int: the number of pairs
*/
// Solution
function divisibleSumPairs($n, $k, $ar) {
$counter = 0;
$matched = [];
for($i = 0; $i < $n; $i++){
for($j = 0; $j < $n; $j++){
if($i != $j){
if(($ar[$i] + $ar[$j]) == $k || (abs($ar[$i] + $ar[$j]) % $k) == 0){
$counter++;
}
}
}
}
return abs($counter/2);
}
$n = 6;
$k = 3;
$ar = [1, 3, 2, 6, 1, 2];
echo divisibleSumPairs($n, $k, $ar);
?>