Skip to content

Commit

Permalink
Update Pow and Sqrt function
Browse files Browse the repository at this point in the history
  • Loading branch information
debapriyo007 committed Apr 5, 2024
1 parent 6dc0834 commit ab0bf7b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
17 changes: 17 additions & 0 deletions 24_MATHS/POW.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,21 @@ public static double powerExponential(double x, int n){
return ans;
}
}

//brute force
public static double power(double x, int n){
double ans = 1;
long m = n;
if(m<0){
m = (-1)*m;
}
for(int i=0; i<m; i++){
ans = ans*x;
}
if(n<0){
return 1/ans;
}else{
return ans;
}
}
}
36 changes: 36 additions & 0 deletions 24_MATHS/Sqrt.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
public class Sqrt {
public static void main(String[] args) {
int n = 169;
System.out.println(findSqrtOptimal(n));
}

// unsing brute froce.
static int findSqrt(int n){
int ans = 0;
for(int i = 1;i<=n;i++){
if(i*i<= n){
ans = i;
}else{
break;
}
}
return ans;
}

static int findSqrtOptimal(int n){
int low = 1;
int high = n;
while (low<= high) {
int mid = low+(high-low)/2;
int val = mid*mid;
if(val == n){
return mid;
}else if(val>n){
high = mid-1;
}else{
low = mid+1;
}
}
return low;
}
}

0 comments on commit ab0bf7b

Please sign in to comment.