I'm using a for-loop
to determine whether the long double
is an int. I have it set up that the for loop loops another long double
that is between 2 and final
^1/2. Final
is a loop I have set up that is basically 2 to the power of 2-10 minus 1. I am then checking if final
is an integer. My question is how can I get only the final
values that are integers?
My explanation may have been a bit confusing so here is my entire loop code. BTW I am using long doubles because I plan on increasing these numbers very largely.
for (long double ld = 1; ld<10; ld++) {
long double final = powl(2, ld) - 1;
//Would return e.g. 1, 3, 7, 15, 31, 63...etc.
for (long double pD = 2; pD <= powl(final, 0.5); pD++) {
//Create new long double
long double newFinal = final / pD;
//Check if new long double is int
long int intPart = (long int)newFinal;
long double newLong = newFinal - intPart;
if (newLong == 0) {
NSLog(@"Integer");
//Return only the final ints?
}
}
}
Just cast it to an int and subtract it from itself?
As a note... because of the way floating point math works in programming, this
==
check isn't necessarily the best thing to do. Better would be to decide on a certain level of tolerance, and check whetherd
was within that tolerance.For example:
You can also use
long long int
andlong double
to accomplish the same thing. Just be sure you're using the right absolute value function for whatever type you're using:fabsf(float)
fabs(double)
fabsl(long double)
EDIT... Based on clarification of the actual problem... it seems you're just trying to figure out how to return a collection from a method.
Stick your logic into this method. Once you've found a number you want to return, stick it into the array using the
[retnArr addObject:[NSNumber numberWithInt:]];
method I put up there.Once you've returned the array, access the numbers like this:
Optionally, you might want to throw them into the
NSNumber
object as different types.You can also use:
[NSNumber numberWithDouble:]
[NSNumber numberWithLongLong:]
And there are matching getters (
doubleValue
,longLongValue
) to extract the number. There are lots of other methods forNSNumber
, but these seem the most likely you'd want to be using.