Question

write a calculator for unlimited digits with linked list by java.

Asked by: andy_09

write a Number class which will allow you to do arithmetic with unlimited digits and accuracy. As an example, this class was used to compute 1000! as:

    40238726007709377354370243392300398571937486421071463254379991042993851239862902
    05920442084869694048004799886101971960586316668729948085589013238296699445909974
    24504087073759918823627727188732519779505950995276120874975462497043601418278094
    64649629105639388743788648733711918104582578364784997701247663288983595573543251
    31853239584630755574091142624174743493475534286465766116677973966688202912073791
    43853719588249808126867838374559731746136085379534524221586593201928090878297308
    43139284440328123155861103697680135730421616874760967587134831202547858932076716
    91324484262361314125087802080002616831510273418279777047846358681701643650241536
    91398281264810213092761244896359928705114964975419909342221566832572080821333186
    11681155361583654698404670897560290095053761647584772842188967964624494516076535
    34081989013854424879849599533191017233555566021394503997362807501378376153071277
    61926849034352625200015888535147331611702103968175921510907788019393178114194545
    25722386554146106289218796022383897147608850627686296714667469756291123408243920
    81601537808898939645182632436716167621791689097799119037540312746222899880051954
    44414282012187361745992642956581746628302955570299024324153181617210465832036786
    90611726015878352075151628422554026517048330422614397428693306169089796848259012
    54583271682264580665267699586526822728070757813918581788896522081643483448259932
    66043367660176999612831860788386150279465955131156552036093988180612138558600301
    43569452722420634463179746059468257310379008402443243846565724501440282188525247
    09351906209290231364932734975655139587205596542287497740114133469627154228458623
    77387538230483865688976461927383814900140767310446640259899490222221765904339901
    88601856652648506179970235619389701786004081188972991831102117122984590164192106
    88843871218556461249607987229085192968193723886426148396573822911231250241866493
    53143970137428531926649875337218940694281434118520158014123344828015051399694290
    15348307764456909907315243327828826986460278986432113908350621709500259738986355
    42771967428222487575867657523442202075736305694988250879689281627538488633969099
    59826280956121450994871701244516461260379029309120889086942028510640182154399457
    15680594187274899809425474217358240106367740459574178516082923013535808184009699
    63725242305608559037006242712434169090041536901059339838357779394109700277534720
    00000000000000000000000000000000000000000000000000000000000000000000000000000000
    00000000000000000000000000000000000000000000000000000000000000000000000000000000
    00000000000000000000000000000000000000000000000000000000000000000000000000000000
    00000000

You will write a (rather feeble) calculator with only a few operations which will do basic arithmetic with these numbers. Running the calculator may give a display like:

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> e
    value: 3.14159265358979323846264338327950288419716939937511
    3.14159265358979323846264338327950288419716939937511

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> m
    value: -20000
    -62831.85307179586476925286766559005768394338798750220000

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> a
    value: .853071
    -62831.0000007958647692528676655900576839433879875022

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> c
    0

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> e
    value: .0000000000000000000000001
    .0000000000000000000000001

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> r
    -.0000000000000000000000001

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> m
    value: 200000
    -.0000000000000000000200000

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> s
    value: -1
    .99999999999999999998

    enter a value: e     add: a
    subtract: s          multiply: m
    reverse sign: r      clear: c
    quit: q
    -> q

You will note that your program will not do division. You can be thankful for this.

The Number class

Numbers will be stored in doubly-linked lists (do not use generics here). Each node will have an int value field which will hold one digit (0 through 9) and two pointer fields, prev and next. The Number class will have five fields:

    private Node low, high;
    private int digitCount = 0;
    private int decimalPlaces = 0;
    private boolean negative = false;

high points to the high-order digit's node, low points to the low-order digit's node, digitCount is the number of digits stored in the list, decimalPlaces is the number of digits (nodes) after the decimal place and negative gives the sign. For example, the number 3.1416 would be represented as:

A number of operations will be provided by public methods:

    * public Number(). A constructor which makes an "empty" Number (with no digits).
    * public Number(String str). A constructor which takes a String representation of a number (e.g. "-21.507"). Calls accept.
    * public void accept(String str). Builds a list representation of the number represented by the string.
    * public Number add(Number n). Returns a Number which represents "this + n".
    * public Number subtract(Number n). Returns a Number which represents "this - n".
    * public Number multiply(Number n). Returns a Number which represents "this * n".
    * public void reverseSign(). Reverses the value of negative.
    * public String toString(). This returns a String representation of the number. It allows you to display a Number using System.out.print().

There will be no other public methods, but you may provide any private methods you wish.

  write methods to manipulate the doubly linked list

need private void insertLow(int digit) and private void insertHigh(int digit) to create and insert new nodes at each end of the list.

write (private) Number addAbsolute(Number n), Number subtractAbsolute(Number n) and int compareToAbsolute(Number n) methods which will perform operations disregarding signs (i.e. the negative field). These can then be called by the public Number add(Number n) and public Number subtract(Number n) methods. The trickiest part of these methods is aligning the decimal points.

create a new (empty) Number sum
int carry = 0
thisPtr = low
nPtr = n.low
while (thisPtr != null)
   add the values stored in the pointed to nodes plus the carry to
                                  get int newDigit
   store newDigit % 10 in a new node inserted at the head of sum
   sum.digitCount++
   store newDigit / 10 in carry
   thisPtr = thisPtr.getPrev()
   nPtr = nPtr.getPrev()
if (carry != 0)
   store carry (1) in new node at the head of sum
   sum.digitCount++
set appropriate value for decimalPlaces in sum


    create a new (empty) Number difference
    int borrow = 0;
    thisPtr = low
    nPtr = n.low
    while (thisPtr != null)
          subtract the pointed to digits and subtract borrow from the result
                           to get int newDigit
          if (newDigit < 0)
             newDigit += 10
             borrow = 1
          else
             borrow = 0
          store newDigit in a new node inserted at the head of difference
          difference.digitCount++
    set appropriate value for decimalPlaces in difference

This code must be adjusted to align decimal points and account for different digit counts.

Multiplication is done in a slightly different way from pencil and paper. We read the first Number to be multiplied from-right-to-left and the second from-left-to-right using "Horner's method."

    create an empty Number product
    let d be the high-order digit of n
    do
       multiply (all of) this by d in a right-to-left manner (with a carry)
                            similar to addAbsolute() to get a Number partialProduct
       multiply product by 10 (just append a new low-order digit 0)
       use addAbsolute() to add partialProduct to product
       let d be the next digit to the right in n
    until you have used all digits of n
    decimalPlaces for product will be the sum of decimalPlaces for this and n
    set product.negative to get the appropriate sign

How can I start with program?  Can you help me.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-17 at 19:52:52ID24742167
Tags

java

Topics

New to Java Programming

,

Java Programming Language

Participating Experts
2
Points
500
Comments
4

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. constructor
    if constructor declar in private part
  2. constructors
    What is the use of having a constructor in a private section.
  3. Words per Minute and accuracy Checking function
    I am trying to write a function to calculate the Words per Minute and accuracy for a typeing tutor program. I don't really understand the concept but I thought about using TStringList components. Will this work? What if I miss a word, how do I check to see if the rest is c...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: rpnmanPosted on 2009-09-17 at 23:27:09ID: 25363267

This is one of the most detailed specifications I've ever seen for an exercise of this sort. Much of the implementation is spelled out for you.

Here is the strategy I would follow for tackling this task:

As a general rule, I would always put unit tests in place every step along the way and keep them in place and regularly execute this. If you do not have a unit test framework (or you have not yet studied that process) then at least add a main method to each class that conducts basic tests on it, and write a few extra integration tests as you go. This can save an enormous amount of time in the long run.

I would start with the digit "node" class. "Digit" might be a better name. Implement and test  the basic ability to hold a value, adding, removing and inserting in a queue. Cover the case of a single digit, then add more.

Building on that I would design the Number class as described. with no operations at all. Consider having it eliminate leading and trailing zeroes automatically to make your job easier, but be sure to handle the case of zero itself as an exception to this rule. (Imply them by the mantissa:  1234 e -8 = 0.00001234).

Perhaps your Number elements should be immutable after the last digit has been added, so the result of any operation is a new Number object. This practice would be consistent with what is done in other solutions like this, and would simplify your task in many ways. If you do this, your constructor should accept all of the digits at once (perhaps as an array or list) to avoid the problem of a partially formed Number.

After getting the basic framework in place, tackle the problem of getting the Number class to display itself correctly. Placing the sign, the decimal point, leading zeroes as needed, etc. This will make further testing easier.

After that add simple magnitude comparison logic and then the operations. I'd start with addition first, as it is by far the easiest. Since you do not have to deal with division, you are NOT faced with the problem of recognizing and dealing with infinitely continuing fractions. That is why the spec says "You can be thankful for this."

Hope this helps.

Have fun. (I mean it.)

// here's a start, not much of a start, but a start  :-)
 
public Digit {
    private final int value;
    private Digit prev;
    private Digit next;
    public Digit(int n) {
        value = n;
        prev = next;
        next = prev;
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: rpnmanPosted on 2009-09-18 at 05:22:06ID: 25365102

After I posted I noticed that the requirements were for a String constructor and an ".accept(String)" method. These, also are consistent with an immutable class, although the .accept method will have to return a new instance in that case, and might as well be a static factory method. (As such it would not conform to standard Java naming conventions, but that's a nit.)

In any case, to build a new Number object as the result of an operation, you'll probably want a private constructor that builds  a number from  an linked list of  Digits, a sign and a mantissa.

I woke up with a clearer picture of another possibility for the constructor of the queue of digits. A special zero digit could serve as the root of the Digit list. It would have to be recognizable (by identity) or by a boolean flag to distinguish it from the other zeroes that just happen to be in the string of digits.

Also - I double checked and I got the terms backward as I 're-purposed' them.

"Characteristic" and "mantissa" classically apply to logarithms. When they do, it is the "mantissa" or integer part which encodes the power of 10, and the "characteristic" or decimal which specifies the series of digits composing the value.

Of course, the numbers you're designing aren't logarithms. Whereas 0.30103 (with a mantissa of 0 and a characteristic of .30103) is an approximation of the log of 2, 3.30103 goes for 2000, etc.  In your case the exponent plays a the notation instead be "0.30103 e 3" for the number 301.03.  

here is a discussion: http://www.tpub.com/math1/9b.htm

I apologize for making the mistake and regret if it caused any confusion.

 

by: ethnarchPosted on 2009-09-18 at 05:25:45ID: 25365131

This looks like homework

 

by: rpnmanPosted on 2009-09-18 at 08:37:05ID: 25367071

Oh, yes, I'd say it did. Thats why I posted textual strategy instead of a coded solution. :-]

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...