Question

use the code and change it Task This assignment is very straight-forward and quick to do...

use the code and change it

Task

This assignment is very straight-forward and quick to do since BigInteger supports integer operations just as long does!

  1. Start by downloading the code below (scroll down). (Certainly compile and run the code to see what it does.)
  2. Add "import java.math.BigInteger;" to the top of the file.
  3. Replace all "Long" types with "BigInteger" in the entire file. (This works because long was intentionally only used for computed values.)
  4. Replace all "long" types with "BigInteger" in the entire file. (This works because long was intentionally only used for computed values.)
  5. Delete all occurrences of ".longValue()" in the value. (Java collections must store objects. Long is a Java-provided class so long values can be stored as objects.)
  6. Replace the two occurrences of 1L passed in to fib_cache.add() with BigInteger.ONE.
  7. Delete the if statements throwing exceptions in fib() and fact().
  8. Delete the "throws AirthmeticException" clauses on the fib() and fact() functions.
  9. Delete the try..catch blocks in main() --but leave the code that is inside the try blocks.
  10. Replace "valueNew = value1 + value2; // fib(i)" with "valueNew = value1.add(value2); // fib(i)". (BigInteger must use its add() method to add values.)
  11. Replace "valueNew = prev*i; // fact(i)" with "valueNew = prev.multiply(BigInteger.valueOf(i)); // fact(i)". (BigInteger must use its multiply() method to multiply values. Note that to convert an int to a BigIInteger one must use the valueOf() static function in BigInteger.)

After these edits, the code will produce the output shown in Sample Output. Notice that the code now shows all iterations of the two for loops. Prof. X' provided code stopped when the result would exceed the maximum value of long.

Sample Output

The following is what will be output from the completed program:

fib(0) = 1
fib(1) = 1
fib(2) = 2
fib(3) = 3
fib(4) = 5
fib(5) = 8
fib(6) = 13
fib(7) = 21
fib(8) = 34
fib(9) = 55
fib(10) = 89
fib(11) = 144
fib(12) = 233
fib(13) = 377
fib(14) = 610
fib(15) = 987
fib(16) = 1597
fib(17) = 2584
fib(18) = 4181
fib(19) = 6765
fib(20) = 10946
fib(21) = 17711
fib(22) = 28657
fib(23) = 46368
fib(24) = 75025
fib(25) = 121393
fib(26) = 196418
fib(27) = 317811
fib(28) = 514229
fib(29) = 832040
fib(30) = 1346269
fib(31) = 2178309
fib(32) = 3524578
fib(33) = 5702887
fib(34) = 9227465
fib(35) = 14930352
fib(36) = 24157817
fib(37) = 39088169
fib(38) = 63245986
fib(39) = 102334155
fib(40) = 165580141
fib(41) = 267914296
fib(42) = 433494437
fib(43) = 701408733
fib(44) = 1134903170
fib(45) = 1836311903
fib(46) = 2971215073
fib(47) = 4807526976
fib(48) = 7778742049
fib(49) = 12586269025
fib(50) = 20365011074
fib(51) = 32951280099
fib(52) = 53316291173
fib(53) = 86267571272
fib(54) = 139583862445
fib(55) = 225851433717
fib(56) = 365435296162
fib(57) = 591286729879
fib(58) = 956722026041
fib(59) = 1548008755920
fib(60) = 2504730781961
fib(61) = 4052739537881
fib(62) = 6557470319842
fib(63) = 10610209857723
fib(64) = 17167680177565
fib(65) = 27777890035288
fib(66) = 44945570212853
fib(67) = 72723460248141
fib(68) = 117669030460994
fib(69) = 190392490709135
fib(70) = 308061521170129
fib(71) = 498454011879264
fib(72) = 806515533049393
fib(73) = 1304969544928657
fib(74) = 2111485077978050
fib(75) = 3416454622906707
fib(76) = 5527939700884757
fib(77) = 8944394323791464
fib(78) = 14472334024676221
fib(79) = 23416728348467685
fib(80) = 37889062373143906
fib(81) = 61305790721611591
fib(82) = 99194853094755497
fib(83) = 160500643816367088
fib(84) = 259695496911122585
fib(85) = 420196140727489673
fib(86) = 679891637638612258
fib(87) = 1100087778366101931
fib(88) = 1779979416004714189
fib(89) = 2880067194370816120
fib(90) = 4660046610375530309
fib(91) = 7540113804746346429
fib(92) = 12200160415121876738
fib(93) = 19740274219868223167
fib(94) = 31940434634990099905
fib(95) = 51680708854858323072
fib(96) = 83621143489848422977
fib(97) = 135301852344706746049
fib(98) = 218922995834555169026
fib(99) = 354224848179261915075
fib(100) = 573147844013817084101
fib(101) = 927372692193078999176
fib(102) = 1500520536206896083277
fib(103) = 2427893228399975082453
fib(104) = 3928413764606871165730
fib(105) = 6356306993006846248183
fib(106) = 10284720757613717413913
fib(107) = 16641027750620563662096
fib(108) = 26925748508234281076009
fib(109) = 43566776258854844738105
fact(0) = 1
fact(1) = 1
fact(2) = 2
fact(3) = 6
fact(4) = 24
fact(5) = 120
fact(6) = 720
fact(7) = 5040
fact(8) = 40320
fact(9) = 362880
fact(10) = 3628800
fact(11) = 39916800
fact(12) = 479001600
fact(13) = 6227020800
fact(14) = 87178291200
fact(15) = 1307674368000
fact(16) = 20922789888000
fact(17) = 355687428096000
fact(18) = 6402373705728000
fact(19) = 121645100408832000
fact(20) = 2432902008176640000
fact(21) = 51090942171709440000
fact(22) = 1124000727777607680000
fact(23) = 25852016738884976640000
fact(24) = 620448401733239439360000
fact(25) = 15511210043330985984000000
fact(26) = 403291461126605635584000000
fact(27) = 10888869450418352160768000000
fact(28) = 304888344611713860501504000000
fact(29) = 8841761993739701954543616000000
fact(30) = 265252859812191058636308480000000
fact(31) = 8222838654177922817725562880000000
fact(32) = 263130836933693530167218012160000000
fact(33) = 8683317618811886495518194401280000000
fact(34) = 295232799039604140847618609643520000000
fact(35) = 10333147966386144929666651337523200000000
fact(36) = 371993326789901217467999448150835200000000
fact(37) = 13763753091226345046315979581580902400000000
fact(38) = 523022617466601111760007224100074291200000000
fact(39) = 20397882081197443358640281739902897356800000000

import java.util.ArrayList;

public class BigFibFact
{
private static ArrayList<Long> fib_cache = new ArrayList<Long>();
private static ArrayList<Long> fact_cache = new ArrayList<Long>();

public static long fib(int N) throws ArithmeticException
{
int size = fib_cache.size();

if (N < size)
return fib_cache.get(N).longValue(); // return previously computed answer
else if (fib_cache.isEmpty())
{
// ensure fib_cache contains "base case" entries...
fib_cache.add(0, 1L);
fib_cache.add(1, 1L);
size = fib_cache.size();
}

// Ensure that N >= size...
if (N < size)
return fib_cache.get(N).longValue(); // return previously computed answer

// It is safe to start at size-2 since base case values are present...
int i = size-2;

// Add the first two previously computed values...
long value1 = fib_cache.get(i++).longValue();
long value2 = fib_cache.get(i++).longValue();
long valueNew;


// and then compute fib(i) until i == N...
do
{
if ((Long.MAX_VALUE-value1) < value2)
throw new ArithmeticException("fib("+i+") is too large for long.");

valueNew = value1 + value2; // fib(i)
fib_cache.add(i++, valueNew); // store fib(i) result

// Adjust last two values...
value1 = value2;
value2 = valueNew;
}
while (i <= N);
return valueNew;
}

public static long fact(int N) throws ArithmeticException
{
int size = fact_cache.size();

if (N < size)
return fact_cache.get(N).longValue(); // return previously computed answer
else if (fact_cache.isEmpty())
{
// ensure fact_cache contains "base case" entry...
fact_cache.add(0, 1L);
size = fact_cache.size();
}

// Ensure that N >= size...
if (N < size)
return fact_cache.get(N).longValue(); // return previously computed answer

// It is safe to start at size-1 since base case value is present...
int i = size-1;

// Add the first two previously computed values...
long prev = fact_cache.get(i++).longValue();
long valueNew;

// and then compute fib(i) until i == N...
do
{
if ((Long.MAX_VALUE - prev) / i < prev)
throw new ArithmeticException("fact("+i+") is too large for long.");

valueNew = prev*i; // fact(i)
fact_cache.add(i++, valueNew); // store fact(i) result

// Adjust prev...
prev = valueNew;
}
while (i <= N);
return valueNew;
}

public static final void main(String[] args)
{
try
{
for (int i=0; i != 110; ++i)
System.out.println("fib("+i+") = "+fib(i));
}
catch (ArithmeticException e)
{
}

try
{
for (int i=0; i != 40; ++i)
System.out.println("fact("+i+") = "+fact(i));
}
catch (ArithmeticException e)
{
}
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

import java.math.BigInteger;

public class Exercise
{
   // Returns n-th Fibonacci number
   static BigInteger fib(int n)
   {
       BigInteger value1 = BigInteger.valueOf(1);
       BigInteger value2 = BigInteger.valueOf(1);
       BigInteger valueNew;
  
       for (int j=0 ; j<n ; j++)
       {
if(j==0)
System.out.println("fib(0) = 1");
else if(j==1)
System.out.println("fib(1) = 1");
else{
valueNew = value1.add(value2);
value1 = value2;
value2 = valueNew;
System.out.println("fib(" + j + ") = " + valueNew);
}
}
return BigInteger.valueOf(0);
   }
  
static BigInteger fact(int N)
{
// Initialize result
BigInteger prev = new BigInteger("1"); // Or BigInteger.ONE
BigInteger valueNew;
// Multiply f with 2, 3, ...N
for (int i = 0; i < N; i++)
{
if(i==0)
System.out.println("fact(0) = 1");
else if(i==1)
System.out.println("fact(1) = 1");
else
{
valueNew = prev.multiply(BigInteger.valueOf(i));
prev = valueNew;
System.out.println("fact(" + i + ") = " + valueNew);
}
}
return BigInteger.valueOf(0);
}

   public static void main(String[] args)
   {
       fib(110);
fact(40);
   }
}

OUTPUT:

PLEASE MAKE SURE TO LIKE THE ANSWER. THANKS SO MUCH IN ADVANCE :)

Add a comment
Know the answer?
Add Answer to:
use the code and change it Task This assignment is very straight-forward and quick to do...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This java code won't run and I can't figure out the problem with it. Please help...

    This java code won't run and I can't figure out the problem with it. Please help import java.io.*; import java.util.*; import java.math.*; import java.util.Scanner; public class Fibonacci {    // Returns n-th Fibonacci number    static BigInteger fib(int n)    {        BigInteger[] Fibo = new BigInteger[n+2]; Fibo[0] = BigInteger.ZERO; Fibo[1] = BigInteger.ONE;           for (int j=2 ; j<=n ; j++)        {            Fibo[j] = Fibo[j-1].add(Fibo[j-2]);        }    return (Fibo[n]); }...

  • Could someone re-write this code so that it first prompts the user to choose an option...

    Could someone re-write this code so that it first prompts the user to choose an option from the calculator (and catches if they enter a string), then prompts user to enter the values, and then shows the answer. Also, could the method for the division be rewritten to catch if the denominator is zero. I have the bulk of the code. I am just having trouble rearranging things. ------ import java.util.*; abstract class CalculatorNumVals { int num1,num2; CalculatorNumVals(int value1,int value2)...

  • 1. What is output by the following code: ArrayList< Integer > a = new ArrayList< Integer...

    1. What is output by the following code: ArrayList< Integer > a = new ArrayList< Integer >(); ArrayList b = a; a.add(new Integer(4)); b.add(new Integer(5)); a.add(new Integer(6)); a.add(new Integer(7)); System.out.println(b.size()); A)1 B)2 C)3 D)4 E)5 2. Assume the Student and Employee classes each extend the Person class. The Student class overrides the getMoney method in the Person class. Consider the following code:     Person p1, p2, p3;     int m1, m2, m3;     p1 = new Person();     m1 = p1.getMoney();     // assignment 1...

  • Please help me finish my code. Before the final pause in the main function, create an...

    Please help me finish my code. Before the final pause in the main function, create an ArrayList of another type such as double, char, short, bool, float, etc. Your choice. Add five data items to your array as we did for the int and string array lists. Print them out with a for loop as we did before. Print out the count and capacity of your new array list. Source.cpp #include #include #include #include "ArrayList.h" using namespace std; /// Entry...

  • Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list....

    Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list. This is only supposed to use THAT method, calling a normal Stack will give me a zero. I do have the conversion to postfix, but there may be error in there. But the main problem currently is the evaluation of postfix. I keep getting an error that I made for an empty stack, which I will include. For testing it is only supposed to...

  • How do I write this code from while loop to for loop? (this is the whole...

    How do I write this code from while loop to for loop? (this is the whole code) NOTE: do not add any import other than: import java.util.ArrayList; import java.util.Collection;(collection not collections) import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.HashSet; code: public static int frequency(Collection values, int target) { var iter = values.iterator(); int app = 0; while (iter.hasNext()) { if(iter.next() == target) { app++; } } return app; } public static boolean isSorted(List list) { var iter = list.listIterator(); int...

  • How do i rewrite this code only using the list below? import java.util.ArrayList; import java.util.Collection; import...

    How do i rewrite this code only using the list below? import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.HashSet; public class RotationCheck {    /**    * Rotates the elements in the specified list by the specified distance. After calling this    * method, the element at index {@code i} will be the element previously at index    * {@code (i - distance) % list.size()}, for all values of {@code i} between {@code 0} and    * {@code...

  • LAB: Zip code and population (generic types)

    13.5 LAB: Zip code and population (generic types)Define a class StatePair with two generic types (Type1 and Type2), a constructor, mutators, accessors, and a printInfo() method. Three ArrayLists have been pre-filled with StatePair data in main():ArrayList<StatePair> zipCodeState: Contains ZIP code/state abbreviation pairsArrayList<StatePair> abbrevState: Contains state abbreviation/state name pairsArrayList<StatePair> statePopulation: Contains state name/population pairsComplete main() to use an input ZIP code to retrieve the correct state abbreviation from the ArrayList zipCodeState. Then use the state abbreviation to retrieve the state name from the ArrayList abbrevState. Lastly,...

  • Can I get help with implementing a quick sort in my program? Starter Code: import java.util.Random;...

    Can I get help with implementing a quick sort in my program? Starter Code: import java.util.Random; import java.util.Scanner; import java.util.Arrays; import java.util.Collections; import java.util.ArrayList; public class RQS { public static int[] prepareData(int[] patients){ /* Data is prepared by inserting random values between 1 and 1000. Data items may be assumed to be unique. Please refer to lab spec for the problem definiton. */ // what is our range? int max = 1000; // create instance of Random class Random randomNum...

  • Currently working on a Java Assignment. I have written most codes for swap, reverse and insert....

    Currently working on a Java Assignment. I have written most codes for swap, reverse and insert. Just need a. itemCount receives a value and returns a count of the number of times this item is found in the list. c. sublist receives two indexes and returns an ArrayList of node values from the first index to the second index, provided the indexes are valid. d. select receives a variable number of indexes, and returns an ArrayList of node values corresponding...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT