-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquareRootAlgo.java
More file actions
52 lines (33 loc) · 1.03 KB
/
SquareRootAlgo.java
File metadata and controls
52 lines (33 loc) · 1.03 KB
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
52
import java.util.*;
public class SquareRootAlgo {
static public int AddQuery (int [] arr , int []blocks , int sqrt , int l , int r) {
int ans = 0 ;
// adding left part
while (l % sqrt != 0 || l< r || l!= 0) {
ans += arr[l++];
}
// adding mid part
while (l+sqrt <= r) {
ans += blocks[l/sqrt];
l+=sqrt;
}
// adding right
while (l <= r){
ans += arr[l++];
}
return ans ;
}
public static void main(String[] args) {
int [] arr = {1,3,5,2,7,6,3,1,4,8};
int n = arr.length ;
int sqrt = (int) Math.sqrt(n);
int block_id = -1 ;
int [] blocks = new int[sqrt + 1];
for (int i = 0 ; i < n ;i++){
if (i % sqrt == 0) block_id++ ;
blocks[block_id] += arr[i];
}
int a = AddQuery(arr, blocks, sqrt, 2, 7);
System.out.println(a);
}
}