-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNaturalNumber.java
executable file
·533 lines (400 loc) · 15 KB
/
NaturalNumber.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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/*
* STUDENT NAME :Mert Gurkan
* STUDENT ID :260716883
*
* If you have any issues that you wish the T.A.s to consider, then you
* should list them here. If you discussed on the assignment in depth
* with another student, then you should list that student's name here.
* We insist that you each write your own code. But we also expect
* (and indeed encourage) that you discuss some of the technical
* issues and problems with each other, in case you get stuck.
*
*/
import java.util.LinkedList;
public class NaturalNumber {
/*
*
* If the list has N coefficients, then then the number is represented is a polynomial:
* coefficients[N-1] base^{N-1} + ... coefficients[1] base^{1} + coefficients[0]
* where base has a particular value and the coefficients are in {0, 1, ... base - 1}
*
* For any base and any positive integer, the representation of that positive
* integer as a sum of powers of that base is unique.
*
* We require that the coefficient of the largest power is non-zero.
* For example, '354' is a valid representation (which we call "three hundred fifty four")
* but '0354' is not.
*
*/
private int base;
private LinkedList<Integer> coefficients;
// Constructors
NaturalNumber(int base){
// If no string argument is given, then it constructs an empty list of coefficients.
this.base = base;
coefficients = new LinkedList<Integer>();
}
/*
* The constructor builds a LinkedList of Integers where the integers need to be in {0,1,2,3,4...,base-1}.
* The string only represents a base 10 number when the base is given to be 10.
*/
NaturalNumber(String sBase, int base) throws Exception{
int i;
this.base = base;
coefficients = new LinkedList<Integer>();
if ((base <2) || (base > 10)){
System.out.println("constructor error: base must be between 2 and 10");
throw new Exception();
}
/*
* The large integer inputs will be read in as strings with character digits.
* These characters will need to be converted to integers. The characters are represented
* in ASCII. See the decimal (dec) and character (char) values in
* http://www.asciitable.com/ ). The ASCII value of symbol '0' is 48, and the ASCII value
* of symbol '1' is 49, etc. So for example to get the numerical value of '2', we subtract
* the character value of '0' (48) from the character value of '2' (50).
*/
int l = sBase.length();
for (int indx = 0; indx < l; indx++){
i = sBase.charAt(indx);
if ( (i >= 48) && (i - 48 < base))
coefficients.addFirst( new Integer(i-48) );
else{
System.out.println("constructor error: all coefficients should be non-negative and less than base");
throw new Exception();
}
}
}
/*
* Construct a NaturalNumber object for a number that has just one digit in [0, base).
*
* This constructor acts as a helper. It is not called from the Tester class.
*/
NaturalNumber(int i, int base) throws Exception{
this.base = base;
coefficients = new LinkedList<Integer>();
if ((i >= 0) && (i < base))
coefficients.addFirst( new Integer(i) );
else {
System.out.println("constructor error: all coefficients should be non-negative and less than base");
throw new Exception();
}
}
/*
* The plus method computes this.plus(b), that is, a+b where 'this' is a.
*
* If you do not know what the Java keyword 'this' is, then see
* https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
*
*/
/*
* Getter for both the private variables- Added by Navin/Ramchalam for testGrader
*/
public int getBase()
{
return base;
}
public LinkedList<Integer> getCoefficients()
{
return coefficients;
}
//To perform a+b, call a.plus(b). The parameter second refers to the second operand in a+b, that is, b
public NaturalNumber plus( NaturalNumber second) throws Exception{
// initialize the sum as an empty list of coefficients
NaturalNumber sum = new NaturalNumber( this.base );
if (this.base != second.base){
System.out.println("ERROR: bases must be the same in an addition");
throw new Exception();
}
/*
* The plus method must not affect the numbers themselves.
* So let's just work with a copy (a clone) of the numbers.
*/
NaturalNumber firstClone = this.clone();
NaturalNumber secondClone = second.clone();
/*
* If the two numbers have a different polynomial order
* then pad the smaller one with zero coefficients.
*/
int diff = firstClone.coefficients.size() - second.coefficients.size();
while (diff < 0){ // second is bigger
firstClone.coefficients.addLast(0);
diff++;
}
while (diff > 0){ // this is bigger
secondClone.coefficients.addLast(0);
diff--;
}
// ADD YOUR CODE HERE
// --------- BEGIN SOLUTION (plus) ----------
int carrier=0;
int size=firstClone.coefficients.size();
for(int i=0;i<size;i++){
int add= (firstClone.coefficients.get(i)+secondClone.coefficients.get(i)+carrier);
sum.coefficients.add(add%this.base);
carrier=add/this.base;
}
while(carrier !=0){
sum.coefficients.add(carrier);
}
// Note 'firstClone' and 'secondClone' have the same size. We add the coefficients
// term by term. If the last coefficient yields a carry, then we add
// one more term with the carry.
// --------- END SOLUTION (plus) ----------
return sum;
}
/*
* Slow multiplication algorithm, mentioned in lecture 1.
* You need to implement the plus algorithm in order for this to work.
*
* 'this' is the multiplicand i.e. a*b = a+a+a+...+a (b times) where a is multiplicand and b is multiplier
*/
public NaturalNumber slowTimes( NaturalNumber multiplier) throws Exception{
NaturalNumber prod = new NaturalNumber(0, this.base);
NaturalNumber one = new NaturalNumber(1, this.base);
for (NaturalNumber counter = new NaturalNumber(0, this.base); counter.compareTo(multiplier) < 0; counter = counter.plus(one) ){
prod = prod.plus(this);
}
return prod;
}
/*
* The multiply method must NOT be the same as what you learned in grade school since
* that method uses a temporary 2D table with space proportional to the square of
* the number of coefficients in the operands i.e. O(N^2). Instead, you must write a method
* that uses space that is proportional to the number of coefficients i.e. O(N).
* Your algorithm will still take time O(N^2) however.
*/
/* The multiply method computes this.multiply(b) where 'this' is a.
*/
public NaturalNumber times( NaturalNumber multiplicand) throws Exception{
// initialize product as an empty list of coefficients
NaturalNumber product = new NaturalNumber( this.base );
if (this.base != multiplicand.base){
System.out.println("ERROR: bases must be the same in a multiplication");
throw new Exception();
}
// ADD YOUR CODE HERE
// -------------- BEGIN SOLUTION (multiply) ------------------
/*
* multiplicand
* x multiplier (this)
* ---------------
*
* Note we use a helper method. See below.
*/
NaturalNumber temp = new NaturalNumber(this.base);
for (int i = 0; i < this.coefficients.size(); i++){
temp = multiplicand.timesSingleDigit(this.coefficients.get(i), i);
product = temp.plus(product);
}
// --------------- END SOLUTION (multiply) -------------------
return product;
}
// -------- BEGIN SOLUTION *helper method* for multiply -----
/*
* 'this' (the caller) will be the multiplicand.
*/
public NaturalNumber timesSingleDigit(int digit, int index){
int c = 0 ;
int p= 0 ;
int temp=0;
int t=0;
NaturalNumber pro = new NaturalNumber(this.base);
for(int i=0 ; i < this.coefficients.size() ; i++ ){
p = this.coefficients.get(i) * digit;
temp = p % base;
pro.coefficients.addLast(temp+c);
c = p / this.base;
}
pro.coefficients.addLast(c);
for(int k=0 ; k<index; k++){
pro.coefficients.addFirst(t);
}
while ((pro.coefficients.size()>1) &
(pro.coefficients.getLast().intValue()==0)){
pro.coefficients.removeLast();
}
return pro;
}
// END SOLUTION ---------- *helper method* for multiply ---------
/*
* The minus method computes this.minus(b) where 'this' is a, and a > b.
* If a < b, then it throws an exception.
*
*/
public NaturalNumber minus(NaturalNumber second) throws Exception{
// initialize the result (difference) as an empty list of coefficients
NaturalNumber difference = new NaturalNumber(this.base);
if (this.base != second.base){
System.out.println("ERROR: bases must be the same in a subtraction");
throw new Exception();
}
/*
* The minus method is not supposed to change the numbers.
* But the grade school algorithm sometimes requires us to "borrow"
* from a higher coefficient to a lower one. So we work
* with a copy (a clone) instead.
*/
NaturalNumber first = this.clone();
// You may assume 'this' > second.
if (this.compareTo(second) < 0){
System.out.println("Error: the subtraction a-b requires that a > b");
throw new Exception();
}
// ADD YOUR CODE HERE
// --------- BEGIN SOLUTION (minus) ----------
int z=first.coefficients.size();
do{
second.coefficients.addLast(0);
}while(z>second.coefficients.size());
int borrowed=0;
for(int i=0; i<z; i++){
if(first.coefficients.get(i)>=second.coefficients.get(i)){
int subtract=first.coefficients.get(i)-second.coefficients.get(i);
difference.coefficients.add(subtract);
}
else {
int subtract = (first.coefficients.get(i)-second.coefficients.get(i)+this.base);
borrowed =-1;
difference.coefficients.add(subtract);
first.coefficients.set(i+1,first.coefficients.get(i+1)+borrowed );
}
}
// --------- END SOLUTION (minus) ----------
/*
* In the case of say 100-98, we will end up with 002.
* Remove all the leading 0's of the result.
*
* We are giving you this code because you could easily neglect
* to do this check, which would mess up grading since correct
* answers would appear incorrect.
*/
while ((difference.coefficients.size() > 1) &
(difference.coefficients.getLast().intValue() == 0)){
difference.coefficients.removeLast();
}
return difference;
}
/*
* Slow division algorithm, mentioned in lecture 1.
*/
public NaturalNumber slowDivide( NaturalNumber divisor) throws Exception{
NaturalNumber quotient = new NaturalNumber(0,base);
NaturalNumber one = new NaturalNumber(1,base);
NaturalNumber remainder = this.clone();
while ( remainder.compareTo(divisor) >= 0 ){
remainder = remainder.minus(divisor);
quotient = quotient.plus(one);
}
return quotient;
}
/*
* The divide method divides 'this' by 'divisor' i.e. this.divide(divisor)
* When this method terminates, there is a remainder but it is ignored (not returned).
*
*/
public NaturalNumber divide( NaturalNumber divisor ) throws Exception{
// initialize quotient as an empty list of coefficients
NaturalNumber quotient = new NaturalNumber(this.base);
if (this.base != divisor.base){
System.out.println("ERROR: bases must be the same in an division");
throw new Exception();
}
if(divisor.compareTo(new NaturalNumber(0, this.base))==0){
System.out.println("ERROR: division by zero not possible");
throw new Exception();
}
NaturalNumber remainder = this.clone();
// ADD YOUR CODE HERE.
// --------------- BEGIN SOLUTION (divide) --------------------------
for(int i=0;i<divisor.coefficients.size();i++){
int xy=this.coefficients.get(i)/(1+divisor.coefficients.get(i));
quotient.coefficients.addLast(xy);
}
// ------------- END SOLUTION (divide) ---------------------
return quotient;
}
// Helper methods
/*
* The methods you write to add, subtract, multiply, divide
* should not alter the two numbers. If a method require
* that one of the numbers be altered (e.g. borrowing in subtraction)
* then you need to clone the number and work with the cloned number
* instead of the original.
*/
@Override
public NaturalNumber clone(){
// For technical reasons that don't interest us now (and perhaps ever), this method
// has to be declared public (not private).
NaturalNumber copy = new NaturalNumber(this.base);
for (int i=0; i < this.coefficients.size(); i++){
copy.coefficients.addLast( new Integer( this.coefficients.get(i) ) );
}
return copy;
}
/*
* The subtraction method (minus) computes a-b and requires that a>b.
* The a.compareTo(b) method is useful for checking this condition.
* It returns -1 if a < b, it returns 0 if a == b,
* and it returns 1 if a > b.
*
* The compareTo() method assumes that the two numbers have the same base.
* One could add code to check this but I didn't.
*/
private int compareTo(NaturalNumber second){
// if this < other, return -1
// if this > other, return 1
// otherwise they are equal and return 0
// Assume maximum degree coefficient is non-zero. Then, if two numbers
// have different maximum degree, it is easy to decide which is larger.
int diff = this.coefficients.size() - second.coefficients.size();
if (diff < 0)
return -1;
else if (diff > 0)
return 1;
else {
// If two numbers have the same maximum degree, then it is a bit trickier
// to decide which number is larger. You need to compare the coefficients,
// starting from the largest and working toward the smallest until you find
// coefficients that are not equal.
boolean done = false;
int i = this.coefficients.size() - 1;
while (i >=0 && !done){
diff = this.coefficients.get(i) - second.coefficients.get(i);
if (diff < 0){
return -1;
}
else if (diff > 0)
return 1;
else{
i--;
}
}
return 0; // if all coefficients are the same, so numbers are equal.
}
}
/* computes 'this' * base^n
*/
private NaturalNumber timesBaseToThePower(int n){
for (int i=0; i< n; i++){
this.coefficients.addFirst(new Integer(0));
}
return this;
}
/*
The following method is invoked by System.out.print.
It returns the string with coefficients in the reverse order
which is the natural format for people to reading numbers,
i.e. people want to read a[N-1], ... a[2] a[1] a[0].
It does so simply by make a copy of the list with elements in
reversed order, and then printing the list using the LinkedList's
toString() method.
*/
@Override
public String toString(){
String s = new String();
for (Integer coef : coefficients) // Java enhanced for loop
s = coef.toString() + s ; // Append each successive coefficient.
return "(" + s + ")_" + base;
}
}