I am just beginning programming and for my first project, I decided to write a program for finding the greatest common divisor using the Euclidean division algorithm in c.
Now though, I want to extend the problem to save the intermittent quotients, remainders, dividends and divisors so that I can use them.
My thought was that I could add something to the inner loop that would put each of the four variables into one row of the array and then start a new row for the next iteration of the loop.
Here’s what I have so far.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool =[[NSAutoreleasePool alloc]init];
NSMutableArray * numberSaver=[[NSMutableArray alloc] init];
NSNumber * q;
NSNumber * end;
NSNumber * or;
NSNumber * rem;
int a,b, divisor, dividend, quotient, remainder, temp, gcd, row;
//get the two numbers
NSLog(@"of which 2 numbers whould you like the GCD?");
scanf("%u%u", &a,&b);
//make the bigger number the dividend, smaller divisor
if (a>b) {
dividend=a;
divisor=b;
} else {
dividend=b;
divisor=a;
}
remainder=1;
row=0;
while (remainder !=0) {
quotient=1;
temp=divisor;
while (temp<dividend) {
temp+=divisor;
++quotient;
}
q=[NSNumber numberWithInt:quotient];
end=[NSNumber numberWithInt: dividend];
or=[NSNumber numberWithInt: divisor];
//set NSNumber objects q, end, or to the integer values at quotient dividend and divisor
gcd=divisor;
//This is so that we can save divisor to be the GCD and not change it to 0 before it is printed
remainder=quotient*divisor - dividend;
rem=[NSNumber numberWithInt:remainder];
//point to the remainder as an object
dividend= divisor;
divisor= remainder;
//Get dividend and divisor ready for the next loop
//I'd like to start adding the newly created NSNumbers to numberSaver here
[numberSaver addObject:quotient atIndex:row:0];
}
NSLog(@"gcd= %u",gcd);
[pool drain] ;
return 0;
}
I’d suggest creating a mutable dictionary with each iteration of the loop and, after adding all the numbers to that, put it into the “master” array:
Storing these things in a dictionary rather than an array means that you don’t have to remember the order in which you added them (
divisorbeforedividend, e..g). Instead, you access them by the key. Later, you can get the values for any given iteration out of the array:Please comment if any of this needs explication.