-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathMathsForDSA.java
More file actions
108 lines (95 loc) · 2.46 KB
/
MathsForDSA.java
File metadata and controls
108 lines (95 loc) · 2.46 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// decimalno,base
// power=0 ans=0
// while(decimal_no>0){
// int rem=decimal_no%base;
// decimal_no=decimal_no/base;
// ans+=rem*Math.pow(10,power);
// power++;
// }
// }
// a,b
// while(b>0){
// if(b%2!=0){
// res=res*a;
// }
// b=b/2;
// a=a*a;
// }
// }
// 2,5
// res=2
// b=2
// a=4
// b=1
// a=16
// res=32
// a=16*16
// final-------------------res=32
public class MathsForDSA {
public static void main(String[] args) {
decimalToAnyBase(5,2);
AnyBaseToDecimal(101,2);
fastExponentiation(2,3);
findEvenOdd(7);
reverseNum(20461);
power(10,6);
}
static void decimalToAnyBase(int decimalNum, int base) {
int resNum = 0;
int power = 0;
while (decimalNum>0){
int rem = decimalNum%base;
decimalNum /= base;
resNum += rem * power(10,power);
power++;
}
System.out.println("Result is "+ resNum);
}
static void AnyBaseToDecimal(int binaryNum, int base) {
int resNum = 0;
int power = 0;
while (binaryNum>0){
int unitDigit = binaryNum %10;
binaryNum /=10;
resNum += unitDigit * power(base,power);
power++;
}
System.out.println("Result is "+ resNum);
}
static void findEvenOdd(int num){
if(num%2 == 0){
System.out.println("even");
}else{
System.out.println("odd");
}
}
static void reverseNum(int num){
int revNum = 0;
while (num > 0 ){
int digit = num %10;
revNum = revNum*10 + digit;
num /=10;
}
System.out.println("Reverse is: "+ revNum);
}
static double power(int num, int power){
double res = 1;
for(int i = 0; i< power;i++){
res = res*num;
}
System.out.println(res);
return res;
}
static double fastExponentiation(int num, int power){
double res = 1;
while (power > 0){
if(power %2!=0){
res = res *num;
}
power /= 2;
num = num *num;
}
System.out.println(res);
return res;
}
}