NSNumberFormatter class not rounding up to correct value - nsstring

I am using NSNumberFormatter class to round a decimal number upto 2 digits and choosing the higher number while rounding up.
NSString *value = #"1054.705";
NSNumberFormatter *valueDouble = [[NSNumberFormatter alloc] init];
valueDouble.roundingMode = NSNumberFormatterRoundCeiling;
[valueDouble setMaximumFractionDigits:2];
NSNumber *myNumber = [valueDouble numberFromString:value];
Desired Output : 1054.71
Output Coming : 1054.705
So in this case round of 0.705 will always should be 0.71 what ever be the digits at the end.

You can handle such cases using this approach - check if second (or whatever) fraction digit is zero and ceil it than divide back
if ((NSInteger)(myNumber.doubleValue * 100) % 10 == 0) {
myNumber = #(ceil(myNumber.doubleValue * 100) / 100);
}

Related

How many zero total in 100 factorial

I have a homework that count total zero in n factorial. What should i do?
I only find way to count trailing of factorial
static int findTrailingZeros(int n)
{
// Initialize result
int count = 0;
// Keep dividing n by powers
// of 5 and update count
for (int i = 5; n / i >= 1; i *= 5)
count += n / i;
return count;
}
The total number of zeros in n! is given by sequence A027869 in the On-line Encyclopedia of Integer Sequences. There really seems to be no way to compute the total number of zeros in n! short of computing n! and counting the number of zeros. With a big int library, this is easy enough. A simple Python example:
import math
def zeros(n): return str(math.factorial(n)).count('0')
So, for example, zeros(100) evaluates to 30. For larger n you might want to skip the relatively expensive conversion to a string and get the 0-count arithmetically by repeatedly dividing by 10.
As you have noted, it is far easier to compute the number of trailing zeros. Your code, in Python, is essentially:
def trailing_zeros(n):
count = 0
p = 5
while p <= n:
count += n//p
p *= 5
return count
As a heuristic way to estimate the total number of zeros, you can first count the number of trailing zeros, subtract that from the number of digits in n!, subtract an additional 2 from this difference (since neither the first digit of n! nor the final digit before the trailing zeros are candidate positions for non-trailing zeros) and guess that 1/10 of these digits will in fact be zeros. You can use Stirling's formula to estimate the number of digits in n!:
def num_digits(n):
#uses Striling's formula to estimate the number of digits in n!
#this formula, known as, Kamenetsky's formula, gives the exact count below 5*10^7
if n == 0:
return 1
else:
return math.ceil(math.log10(2*math.pi*n)/2 + n *(math.log10(n/math.e)))
Hence:
def est_zeros(n):
#first compute the number of candidate postions for non-trailing zerpos:
internal_digits = max(0,num_digits(n) - trailing_zeros(n) - 2)
return trailing_zeros(n) + internal_digits//10
For example est_zeros(100) evaluates to 37, which isn't very good, but then there is no reason to think that this estimation is any better than asymptotic (though proving that it is asymptotically correct would be very difficult, I don't actually know if it is). For larger numbers it seems to give reasonable results. For example zeros(10000) == 5803 and est_zeros == 5814.
How about this then.
count = 0
s = str(fact)
for i in s:
if i=="0":
count +=1
print(count)
100! is a big number:
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
To be more precise it need ~525 bit and can not be computed without some form of bigint math.
However trailing zeros might be computable on normal integers:
The idea is to limit the result to still fit into your data type. So after each iteration test if the result is divisible by 10. If it is increment your zeros counter and divide the result by 10 while you can. The same goes for any primes except those that divide 10 so not: 2,5 (but without incrementing your zeros counter). This way you will have small sub-result and count of trailing zeros.
So if you do a 2,5 factorization of all the multiplicants in n! the min of the both exponents of 2,5 will be the number of trailing zeros as each pair produces one zero digit (2*5 = 10). If you realize that exponent of 5 is always smaller or equal than exponent of 2 its enough to do the factorization of 5 (just like you do in your updated code).
int fact_trailing_zeros(int n)
{
int i,n5;
for (n5=0,i=5;n>=i;i*=5) n5+=n/i;
return n5;
}
With results:
Trailing zeors of n!
10! : 2
100! : 24
1000! : 249
10000! : 2499
100000! : 24999
1000000! : 249998
10000000! : 2499999
100000000! : 24999999
[ 0.937 ms]
However 100! contains also non trailing zeros and to compute those I see no other way than compute the real thing on a bigint math ... but that does not mean there is no workaround like for trailing zeros...
If it helps here are computed factorials up to 128! so you can check your results:
Fast exact bigint factorial
In case n is bounded to small enough value you can use LUT holding all the factorials up to the limit as strings or BCD and just count the zeros from there... or even have just the final results as a LUT ...
Here some bad code, but it works. You have to use TrailingZeros() only
public static int TrailingZeros(int n)
{
var fac = Factorial(n);
var num = SplitNumber(fac);
Array.Reverse(num);
int i = 0;
int res = 0;
while (num[i] == 0)
{
if (num[i] == 0)
{
res++;
}
i++;
}
return res;
}
public static BigInteger Factorial(int number)
{
BigInteger factorial = 1; // значение факториала
for (int i = 2; i <= number; i++)
{
factorial = factorial * i;
}
return factorial;
}
public static int[] SplitNumber(BigInteger number)
{
var result = new int[0];
int count = 0;
while (number > 0)
{
Array.Resize(ref result, count + 1);
result[count] = (int)(number % 10);
number = number / 10;
count++;
}
Array.Reverse(result);
return result;
}

Limit a value between min and max using only arithmetic

Is it possible to limit a value in a given range, between min and max, using only arithmetic? That is, + - x / and %?
I am not able to use functions such as min, max nor IF-statements.
Let's assume I have a range of [1850, 1880], for any values < 1850, it should display 1850. For values > 1880, 1880 should be displayed. It would also be acceptable if only 1850 was displayed outside the range.
I tried:
x = (((x - xmax) % (xmax - xmin)) + (xmax - xmin)) % (xmax - xmin) + xmin
but it gives different values in the middle of the range for values lower than xmin.
If you know the size of the integer type, you can extract its sign bit (assuming two's complement) using integer division:
// Example in C
int sign_bit(int s)
{
// cast to unsigned (important)
unsigned u = (unsigned)s;
// number of bits in int
// if your integer size is fixed, this is just a constant
static const unsigned b = sizeof(int) * 8;
// pow(2, b - 1)
// again, a constant which can be pre-computed
static const unsigned p = 1 << (b - 1);
// use integer division to get top bit
return (int)(u / p);
}
This returns 1 if s < 0 and 0 otherwise; it can be used to calculate the absolute value:
int abs_arith(int v)
{
// sign bit
int b = sign_bit(v);
// actual sign (+1 / -1)
int s = 1 - 2 * b;
// sign(v) * v = abs(v)
return s * v;
}
The desired function looks like this:
It is useful to first shift the minimum to zero:
This function form can be computed as a sum of the two shifted absolute value functions below:
However the resultant function is scaled by a factor of 2; shifting to zero helps here because we only need to divide by 2, and shift back to the original minimum:
// Example in C
int clamp_minmax(int val, int min, int max)
{
// range length
int range = max - min;
// shift minimum to zero
val = val - min;
// blue function
int blue = abs_arith(val);
// green function
int green = range - abs_arith(val - range);
// add and divide by 2
val = (blue + green) / 2;
// shift to original minimum
return val + min;
}
This solution, although satisfies the requirements of the problem, is limited to signed integer types (and languages which allow integer overflow - I'm unsure of how this could be overcome in e.g. Java).
I found this while messing around in... excel. It only works for strictly positive integers. Although this is not more restrictive as the answer by meowgoesthedog because he also effectivly halves the integer space by dividing by two at the end. It doesn't use mod.
//A = 1 if x <= min
//A = 0 if x >= min
A = 1-(min-min/x)/min
//B = 0 if x <= max
//B = 1 if x > max
B = (max-max/x)/max
x = A*min + (1-A)*(1-B)*x + B*max
I found this solution in Python:
A = -1 # Minimum value
B = +1 # Maximum value
x = min(max(x, A), B)

How to get the last digit of a number without using modulus(%) operator?

If we are told that we can't use modulus operator then how can we take
out the last digit of a number.
e.g.
N=2345, we should get 5.
Try to provide a generic solution.
What I found:
N- N/ 10 * 10
The formula you provided will work.
Generally speaking, for Integers >= 0 this will always be true
A % B = A - [A/B] * B, where [x] denotes greatest integer <= x
http://jsfiddle.net/e51mg205/
number = 2345;
arr = (""+number).split('');
console.log(arr[arr.length-1])
By casting.
but this require some checks before.
simple example:
int num = 15;
double d = num/10; //d = 1.5
num = num/10; //num = 1;
int lastNumber = (d - (double)num) * 10;

Finding the tenth's place equivalent of an integer

How does one, computationally and dynamically, derive the 'ths' place equivalent of a whole integer? e.g.:
187 as 0.187
16 as 0.16
900041 as 0.900041
I understand one needs to compute the exact th's place. I know one trick is to turn the integer into a string, count how many places there are (by how many individual characters there are) and then create our future value to multiply against by the tenth's value derived - like how we would on pen and paper - such as:
char integerStr[7] = "186907";
int strLength = strlen(integerStr);
double thsPlace = 0.0F;
for (int counter = 0; counter < strLength; ++counter) {
thsPlace = 0.1F * thsPlace;
}
But what is a non-string, arithmetic approach to solving this?
pseudocode:
n / pow(10, floor(log10(n))+1)
Divide the original value by 10 repeatedly until it's less than one:
int x = 69105;
double result = (double) x;
while (x > 1.0) x /= 10.0;
/* result = 0.69105 */
Note that this won't work for negative values; for those, you need to perform the algorithm on the absolute value and then negate the result.
[edited for strange indenting]
I'm not sure exactly what you mean with your question, but here's what I would do:
int placeValue(int n)
{
if (n < 10)
{
return 1;
}
else
{
return placeValue(n / 10) + 1;
}
}
[This is a recursive method]
I don't know how performant the pow(10, x) version is, but you could try to do most of this with integer arithmetic. Assuming we are only dealing with positive values or 0 (use the absolute value, if necessary):
int divisor = 1;
while (divisor < x)
divisor *= 10;
if (divisor > 0)
return (double)x / divisor;
Note that the above needs some safeguards, i.e. checking if divisor may have overflow (in that case, it would be negative), if x is positive, etc. But I assume you can do that yourself.

Conversion of Double to value digits and exponent

For ex.
double size = 10.35;
i should get
value = 1035;
exponent = -2;
so when i re calculate i will get 10.35.
i.e 1035 * 10^-2 = 10.35;
Please help me.
Thanks in advance
In general this is not possible since the fractional part of a double is stored in powers-of-2, and might or might not match powers-of-10.
For example: When looking at powers-of-2 vs powers-of-3: Just like 1/2 == 2^-1 == 5 * 10^-1 has a match, 1/3 == 3^-1 == ?? does not have a match.
However, you can approximate it.
It would have an answer if you would ask for powers-of-2. In that case you can just look at the double representation (see IEEE-754 here) and extract the right bits.
Very simplistically (in C#):
double size = 10.36;
int power = 0;
while (size != (int)size)
{
size *= 10.0;
power--;
}
Console.WriteLine("{0} * 10 to the {1}", size, power);
Though I'm sure with a bit more thought a more elegant solution can be found.
This doesn't go the other way where you've got a large number (103600 say) and want to get the smallest value to some power (1036 * 10^2).
I had to do something very similar. Here's a solution in Python (it hasn't been tested very well):
def normalize(value, fdigits=2):
"""
Convert a string representing a numerical value to value-digit/exponent form.
Round the fractional portion to the given number of digits.
value the value (string)
fdigits the number of digits to which to round the fractional
portion
"""
# if empty string, return error
if not value:
return None
# split value by decimal
v = value.split('.')
# if too many decimals, return error
if len(v) > 2:
return None
# add empty string for fractional portion if missing
elif len(v) == 1:
v.append('')
# assign whole and fractional portions
(w, f) = v
# pad fractional portion up to number of significant digits if necessary
if len(f) < fdigits:
f += ('0' * (fdigits - len(f)))
# if the number of digits in the fractional portion exceeds the
# number of digits allowed by fdigits
elif len(f) > fdigits:
# convert both portions to integers; use '0' for whole portion if missing
(wi, fi) = (int(w or '0'), int(f[:fdigits]))
# round up if first insignificant digit is gteq 5
if int(f[fdigits]) >= 5:
fi += 1
# roll whole value up if fractional portion rounds to a whole
if len(str(fi)) > fdigits:
wi += 1
fi = 0
# replace the whole and fractional strings
(w, f) = (str(wi), ("%0" + str(fdigits) + "d") % fi)
# derive value digits and exponent
n = w.lstrip() + f
l = len(n)
x = -fdigits
n = n.rstrip('0')
x += (l - len(n))
# return value digits and exponent
return (int(n), x)

Resources