Define a class, which implements arithmetic with arbitrary precision

Discussion in 'Mac Programming' started by haitszon, Aug 30, 2012.

  1. haitszon macrumors newbie

    Aug 30, 2012
    Hi everyone!
    I'm currently doing some exercises in a objective-c book. One of them is: define a class, which implements arithmetic (+, -, /, *, %) with arbitrary precision. This is a new type with just some arithmetic operations. We can do some arithmetic with an infinite precision.
    I'm aware that there exist libraries to do this, but I need to attempt to implement it myself. Is there anyone can help?
    Thanks in advanced!
  2. chown33 macrumors 604

    Aug 9, 2009
  3. haitszon thread starter macrumors newbie

    Aug 30, 2012
    It is just a lab book at my school. I've already read through all these. The task is to implement a class to support arbitrary precision integer arithmetic. In other words, write code to do addition, subtraction, division, multiplication, and modulus for integers at any length for the following interface:

    @interface MPInteger : NSObject

    -(id) initWithString: (NSString *) x;
    -(NSString *) description;

    -(MPInteger *) add: (MPInteger *) x;
    -(MPInteger *) subtract: (MPInteger *) x;
    -(MPInteger *) multiply: (MPInteger *) x;
    -(MPInteger *) divideBy: (MPInteger *) x;
    -(MPInteger *) modulus: (MPInteger *) x;

    -(BOOL) isLessThan: (MPInteger *) x;

    Is there anyone can help? much appreciated if someone can give me some idea to start!
  4. PatrickCocoa macrumors 6502a

    Dec 2, 2008
    Remember elementary school?

    No, not that time you puked in front of the class. You were taught how to add and subtract manually. I'm assuming they still do that, and don't just show you how to hit numbers on a calculator.

    Anyway, just implement that addition algorithm using the string inputs. Pull off each digit, starting at the rightmost (least significant digit), add them (if you have only two operands then you know the result will be at most 18), determine what the carry digit is, and build the answer that way.

    Once you've done addition, then do multiplication. Then subtraction, and finally division.

Share This Page