forked from kepbautista/mycalculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyCalculator.java
66 lines (50 loc) · 1.21 KB
/
MyCalculator.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Author: Kristine Elaine P. Bautista
* Program Description: Calculator of Simple Mathematical Functions
**/
public class MyCalculator {
// add two numbers
public float add(float a,float b){
return a+b;
}
// subtract two numbers
public float subtract(float a,float b){
return a-b;
}
// multiply two numbers
public float multiply(float a,float b){
return a*b;
}
// divide two numbers
public float divide(float a,float b){
return a/b;
}
// x^2 of two numbers
public float square(int x){
return x*x;
}
// x^3 of three numbers
public float cube(int x){
return x*x*x;
}
// n! of an integer
public int nfactorial(int n){
int factorial = 1;
for(int i=1;i<=n;i++) //changed i<n to i<=n
factorial *= i;
return factorial;
}
// binary search in an array
int binarySearch(int[] a,int x){
int n = a.length; // get number of elements in the array
int lower, upper, middle; // variables for positions in the array
lower = 0; upper = n-1; // initialize values of lower and upper points
while(lower<=upper){
middle = (lower+upper)/2;
if(x>a[middle]) lower = middle + 1;
else if(x<a[middle]) upper = middle - 1;
else return middle;
}
return 1;
}
}