Skip to content

Commit 7837e27

Browse files
committed
add binary search function iterative
1 parent 6a37682 commit 7837e27

File tree

2 files changed

+70
-80
lines changed

2 files changed

+70
-80
lines changed

Algorithms/BinarySearch.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/* package joney_000 */
2+
3+
import java.util.*;
4+
import java.lang.*;
5+
import java.io.*;
6+
import java.math.*;
7+
8+
9+
public class Solution
10+
11+
{
12+
13+
public static void main(String[] args)throws Exception
14+
15+
{
16+
17+
/* BufferedReader br=new BufferedReader(new FileReader("input.txt"));
18+
BufferedWriter out=new BufferedWriter(new FileWriter("output.txt"));
19+
*/
20+
21+
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
22+
BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out));
23+
24+
25+
int t = Integer.parseInt(br.readLine());
26+
long arr[] = new long[1000001];
27+
28+
for (long i=1;i<=1000000;i++){
29+
arr[(int)i]=(i*(i+1)*(2*i+1))/6;
30+
}
31+
32+
for (int test=0;test<t;test++){
33+
long x = Long.parseLong(br.readLine());
34+
int idx = Arrays.binarySearch(arr,1,1000000+1,x); // [L..R] = Arrays.binarySearch(arr,l,r+1,key);
35+
if(idx < 0){
36+
idx = -idx;
37+
idx -= 2;
38+
}
39+
long ans = idx ;
40+
out.write(""+ans+"\n");
41+
out.flush();
42+
}
43+
44+
45+
}//end of public static void main();
46+
public static boolean isPrime(long n)throws Exception{
47+
if(n==2||n==3)return true;
48+
for(int i=2;i<=Math.sqrt(n);i++){
49+
if(n%i==0)return false;
50+
}
51+
return true;
52+
}
53+
public static long gcd(long a, long b)throws Exception{
54+
if(b==0)return a;
55+
return gcd(b,a%b);
56+
}
57+
public static long lcm(long a, long b)throws Exception{
58+
if(b==0||a==0)return 0;
59+
return (a*b)/gcd(a,b);
60+
}
61+
public static long pow(long a,long b,long mod)throws Exception{
62+
if(b==1)return a%mod;
63+
if(b==0)return 1;
64+
long ans=pow(a,b/2,mod);
65+
ans=(ans*ans)%mod;
66+
if(b%2!=0)ans=(ans*a)%mod;
67+
68+
return ans;
69+
}
70+
} /

Algorithms/Binary_Iterative.java

Lines changed: 0 additions & 80 deletions
This file was deleted.

0 commit comments

Comments
 (0)