I'm aware of the modular arithmetic approach to solve this question, I just took it upon myself to solve it in the more naive way, but I just created an infinite loop somewhere in the inner for loop and there is no way out (Please do not tell me to do it in the standard way, This is just a challenge that I made upon myself)
The function return the size of a maximal subset of S where the sum of any 2 numbers in sā is not evenly divisible by k.
here is my code that causes an infinite loop, so be careful
function nonDivisibleSubset(arr, k) {
let maxElements = 0;
for (let i = 0; i < arr.length; i++) {
console.log(i);
// arr 1 to (arr.length - 1)
let result = [];
let noOfElements = 0;
for (let j = 0 + 1; j < arr.length; j++) {
console.log(`hi${j}`);
//arr 2 to arr.length
console.log(result.length);
if (
result.length === 0 &&
(arr[i] + arr[j]) % k !== 0
) {
console.log("hi2");
result.push(arr[i], arr[j]);
noOfElements += 2;
} else {
let isDivisible = false;
console.log(`result length: ${result.length}`);
for (let l = 0; l < result.length; l++) {
console.log(l);
if (i !== l && (arr[l] + arr[j]) % 4 === 0) {
isDivisible = true;
break;
}
if (!isDivisible) {
result.push(arr[l]);
console.log(result);
noOfElements += 1;
break; //removing this break will initialize the infinite loop
}
}
}
}
if (noOfElements > maxElements) {
maxElements = noOfElements;
}
}
return maxElements;
}
//initialise
nonDivisibleSubset([19, 10, 12, 10, 24, 25, 22], 4)