# Archive for August, 2010

### % (modulo) operator only works on int and long data types in Objective C 2.0

Posted by Ladislav Klinc in Objective C 2.0 on August 30, 2010

Today, I tried to use a modulo % operator in a function in Objective C 2.0 like so: (Modulo operator finds the remainder of division of one number by another)

-(double) someFunction: (double) value { ... if (value % 90 == 0) return 0; ... }

When I compiled my code, XCode generated and error saying that % function cannot be used for double values. I googled my way on to this stackoverflow question (isn’t it amazing that for almost every problem you have, stackoverflow.com has an answer to your question…), where one of the ways of getting remainder of division where one or both numbers are double is to use c function fmod(). So I rewrote my function and XCode compiled without a problem…

-(double) someFunction: (double) value { ... if (fmod(value,90) == 0) return 0; ... }

### Implementing factorial numbers in Objective C 2.0

Posted by Ladislav Klinc in Objective C 2.0 on August 26, 2010

I was implementing a function that would calculate factorial number for a given positive integer value. Factorial is denoted by n! and is the product of all positive integers less than or equal to n. For example:

6! = 1*2*3*4*5*6 = 720

So I implemented the function factorialX as follows:

-(double) factorialX: (int) value { double tempResult = 1; for (int i=2; i<=value; i++) { tempResult *= i; } return tempResult }

Tried the code out and [self factorialX:6] does return 720 as it should. Then I tried it with bigger numbers, and the first problem noticed was with 13! which returned result 1,932,053,504 but it should have returned 6,227,020,800. Well that is a little bit strange, then I googled factorial a little bit and found this post: Factorial Function in Objective C, and the author points out: “That’s because 13! exceeds unsigned integer maximum of about 4,000 million on 32-bit platforms.”.

Ok, but I have tempResult defined as double, so why did I get the problem that is associated with int. It turns out that in the loop tempResult is multiplied by i (which is defined as int) and thus the whole calculation is done for int values.

The solution is to cast the i as double, thus changing the expression in the loop to:

tempResult *= (double) i;

Then if I try to calculate 13! I get the correct result of 6,227,020,800 🙂

Found that math.h indeed has a gamma function, so I could calculate any factorial n (where n can be any positive number) with lgamma(n+1).

(*One question I have, which maybe of of the readers can solve is, how to calculate factorial of non integer value. For example 6.4!. If you input this into **wolframalpha.com** it shows you the result and it is calculated as Gamma(7.4), since Gamma(n+1) = n!. But **Gamma function** is defined as integral, and I do not know a way to calculate it numerically…*)