<script>
let MAX = 1000;
function
isPerfectSquare(x)
{
let sr = Math.sqrt(x);
return
((sr - Math.floor(sr)) == 0) ?
true
:
false
;
}
function
getMid(s, e) {
return
Math.floor(s + (e - s) / 2);
}
function
queryUtil(st, ss, se, qs, qe, index) {
if
(qs <= ss && qe >= se)
return
st[index];
if
(se < qs || ss > qe)
return
0;
let mid = getMid(ss, se);
return
queryUtil(st, ss, mid, qs,
qe, 2 * index + 1) +
queryUtil(st, mid + 1, se,
qs, qe, 2 * index + 2);
}
function
updateValueUtil(st, ss, se, i, diff, si) {
if
(i < ss || i > se)
return
;
st[si] = st[si] + diff;
if
(se != ss) {
let mid = getMid(ss, se);
updateValueUtil(st, ss, mid, i,
diff, 2 * si + 1);
updateValueUtil(st, mid + 1, se,
i, diff, 2 * si + 2);
}
}
function
updateValue(arr, st, n, i, new_val) {
if
(i < 0 || i > n - 1) {
document.write(
"Invalid Input"
);
return
;
}
let diff = 0, oldValue;
oldValue = arr[i];
arr[i] = new_val;
if
(isPerfectSquare(oldValue) &&
isPerfectSquare(new_val))
return
;
if
(!isPerfectSquare(oldValue) &&
!isPerfectSquare(new_val))
return
;
if
(isPerfectSquare(oldValue) &&
!isPerfectSquare(new_val)) {
diff = -1;
}
if
(!isPerfectSquare(oldValue) &&
!isPerfectSquare(new_val)) {
diff = 1;
}
updateValueUtil(st, 0, n - 1,
i, diff, 0);
}
function
query(st, n, qs, qe) {
let perfectSquareInRange = queryUtil(st, 0,
n - 1,
qs, qe, 0);
document.write(perfectSquareInRange +
"<br>"
);
}
function
constructSTUtil(arr, ss, se, st, si) {
if
(ss == se) {
if
(isPerfectSquare(arr[ss]))
st[si] = 1;
else
st[si] = 0;
return
st[si];
}
let mid = getMid(ss, se);
st[si] = constructSTUtil(arr, ss,
mid, st,
si * 2 + 1) +
constructSTUtil(arr, mid + 1,
se, st, si * 2 + 2);
return
st[si];
}
function
constructST(arr, n) {
let x = (Math.ceil(Math.log(n)));
let max_size = 2 * Math.pow(2, x) - 1;
let st =
new
Array(max_size).fill(0);
constructSTUtil(arr, 0, n - 1, st, 0);
return
st;
}
let arr = [16, 15, 8, 9, 14, 25];
let n = arr.length;
let st = constructST(arr, n);
let start = 0;
let end = 4;
query(st, n, start, end);
let i = 3;
let x = 11;
updateValue(arr, st, n, i, x);
start = 0;
end = 4;
query(st, n, start, end);
</script>