views:

69

answers:

2

Hello.

In objective c (Mac development). How can i find out if a number is divisible by another number and not a decimal?

+10  A: 

Assuming you're dealing with integers, use the modulus function:

if ((a % b) == 0) {
  // A is divisible by B
} else {
  // A isn't divisible by B
}
David Knell
Not working, i've tried if ((1 % 2) == 0) { NSLog(@"1 is divisible by 2"); } else { NSLog(@"1 is NOT divisible by 2"); }
Daniel
+1 - good old classic C language! :-)
Pablo Santa Cruz
@Daniel: And what does that result give you? Divisible or NOT Divisible?
Robin Day
@Robin Nvm fixed it :)
Daniel
Also how would i generate a random number that IS divisible by a certain number?
Daniel
By generating a random number and multiplying it by the number you wish the final result to be divisible by?
Stephen
Right, and 1 isn't divisible by 2 (you can't fit 2 into 1 an exact number of times, you can only fit it in half a time). On the other hand, 2 *is* divisible by 1
Gareth
@Stephen: Awesome answer!!
Robin Day
@Robin Day: I'm not sure if that's sarcasm, but I'll assume not and just go with thanks! =D
Stephen
Black Frog
+1  A: 

I'm not a objective c programmer, but in general, just checking if A mod B = 0 should do it... won't it work in OC?

cheers.

flpgdt