How can I perform division in a program, digit by digit? - c#
I'm messing around with writing a class similar to mpz (C) or BigInteger (Java). This is just for fun, so please don't go on about how I shouldn't be writing my own.
I have a class similar to:
public class HugeInt
{
public List<Integer> digits;
public HugeInt(String value)
{
// convert string value into its seperate digits.
// store them in instance variable above
}
}
Now, doing the add() and subtract() method of this class are pretty simple. Here is an example:
private List<Integer> add(List<Integer> a, List<Integer> b)
{
List<Integer> smallerDigits = (compareDigits(a,b) < 0) ? a : b;
List<Integer> largerDigits = (compareDigits(a,b) >= 0) ? a : b;
List<Integer> result = new ArrayList<Integer>();
int carry = 0;
for(int i = 0; i < largerDigits.size(); i++)
{
int num1 = largerDigits.get(i);
int num2 = (i < smallerDigits.size()) ? smallerDigits.get(i) : 0;
result.add((num1 + num2 + carry) % 10);
carry = ((num1 + num2 + carry) / 10);
}
if (carry != 0) result.add(carry);
return result;
}
Similarly, doing the multiply wasn't that hard either.
I see on wikipedia there is a page on Division Algorithms, but I'm not sure which one is appropriate for what I'm trying to do.
Because these positive integers (represented as digits) can be arbitrarily long, I want to make sure I don't attempt to do any operations on anything other than digit-by-digit basis.
However, can anyone point me in the right direction for doing a division of two numbers that are represented as List<Integer>'s? Also, I can ignore the remainder as this is integer division.
You could just do long division, but this certainly isn't the optimal way to do it (edit: although it seems that something like this is a good way to do it). You could look at other implementations of big integer libraries, and a bit of Googling turns up a fair bit of useful information.
This may be a slight overkill, but if this is the kind of things you do for fun, you'll enjoy reading this:
http://www.fizyka.umk.pl/nrbook/c20-6.pdf
(that's "Arithmetic at Arbitrary Precision" from "Numerical recipes in C").
Pretty fascinating, as is most of this book, with good explanations and lots of code.
Since I assume you're just dealing with integer division it's not very hard. Multiplication is repeated addition, division is the opposite - repeated subtraction. So what you'll do is check how many times you can subtract the divisor from the dividend. For example, 3 can be subtracted from 10 3 times without going <0, so the integer division quotient is 3.
This article A Larger Integer does not show how to implement digit by digit operations for "larger integers", but it does show how to implement a (apparently fully functional) 128 bit integer in terms of two Int64 types. I would imagine that it would not be too hard to extend the approach to use an array of Int64 types to yield an arbitary length integer. I just spent a few minutes looking back over the article and the implementation of multiply looks like it could get pretty involved for arbitrary length.
The article shows how to implement division (quotient and remainder) using binary division.
Related
BigInteger.Pow(BigInteger, BigInteger)?
I'm trying to calculate a large number, which requires BigInteger.Pow(), but I need the exponent to also be a BigInteger and not int. i.e. BigInteger.Pow(BigInteger) How can I achieve this? EDIT: I came up with an answer. User dog helped me to achieve this. public BigInteger Pow(BigInteger value, BigInteger exponent) { BigInteger originalValue = value; while (exponent-- > 1) value = BigInteger.Multiply(value, originalValue); return value; }
Just from the aspect of general maths, this doesn't make sense. That's why it's not implemented. Think of this example: Your BigInteger number is 2 and you need to potentiate it by 1024. This means that the result is a 1 KB number (2^1024). Now imagine you take int.MaxValue: Then, your number will consume 2 GB of memory already. Using a BigInteger as an exponent would yield a number beyond memory capacity! If your application requires numbers in this scale, where the number itself is too large for your memory, you probably want a solution that stores the number and the exponent separately, but that's something I can only speculate about since it's not part of your question. If your your issue is that your exponent variable is a BigInteger, you can just cast it to int: BigInteger.Pow(bigInteger, (int)exponent); // exponent is BigInteger
Pow(2, int64.MaxValue) requires 1,152,921 terabytes just to hold the number, for a sense of scale. But here's the function anyways, in case you have a really nice computer. static BigInteger Pow(BigInteger a, BigInteger b) { BigInteger total = 1; while (b > int.MaxValue) { b -= int.MaxValue ; total = total * BigInteger.Pow(a, int.MaxValue); } total = total * BigInteger.Pow(a, (int)b); return total; }
As others have pointed out, raising something to a power higher than the capacity of int is bad news. However, assuming you're aware of this and are just being given your exponent in the form of a BigInteger, you can just cast to an int and proceed on your merry way: BigInteger.Pow(myBigInt, (int)myExponent); or, even better, try { BigInteger.Pow(myBigInt, (int)myExponent); } catch (OverflowException) { // Do error handling and stuff. }
For me the solution was to use the function BigInteger.ModPow(BigInteger value, BigInteger exponent, BigInteger modulus) because I needed to do a mod afterwards anyway. The function calculates a given BigInteger to the power of another BigInteger and calculates the modulo with a third BitInteger. Although it will still take a good amount of CPU Power it can be evaluated because the function already knows about the modulo and therefore can save a ton of memory. Hope this might help some with the same question. Edit: Is available since .Net Framework 4.0 and is in .Net Standard 1.1 and upwards.
I came up with: public BigInteger Pow(BigInteger value, BigInteger exponent) { BigInteger originalValue = value; while (exponent-- > 1) value = BigInteger.Multiply(value, originalValue); return value; }
1000 digit number in C#
I am working on Project Euler and ran into an issue. I am unable to use a 1000 digit number and wanted to know if I am doing something wrong or am just going about this solution in the wrong way and if so what would be best approach be? C# namespace ToThePowerOf { class Program { static void Main(string[] args) { BigInteger n = 1; int x = 0; BigInteger [] number; number = new BigInteger[149194]; number[x] = 1; number[x + 1] = 1; x = 3; ; BigInteger check = 10000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 00000000000000000000000; for (int i = 99; i > 0; i--) { n = (n - 1) + (n - 2); number[x] = n; x++; if (n > check) { Console.WriteLine(x); } } } } }
I'm guessing the 'issue' you ran into (would be helpful to include error message) is that the compiler doesn't like the integer literal with 1000 digits so you can't initialise it with a very large integer literal. As others have noted, breaking the integer literal into multiple lines isn't valid either. The number[x] = 1; lines work because the compiler can handle the integer literal 1 and because we're assigning it to a BigInteger it uses BigInteger's implicit operator to convert it to a BigInteger. One simple method to get around your problem with the big integer literal is to use the BigInteger.Parse method to create your 1000 digit number. BigInteger check = BigInteger.Parse("10000....", CultureInfo.InvariantCulture); Another method could be to initialise it with a small int, then use maths to get to the number you want, as in Jon Skeet's answer.
There's no literal support for BigInteger in C#. So while using BigInteger isn't incorrect, you'll need to work out a different way of instantiating it - e.g. new BigInteger(10).Pow(1000).
Such a big literal isn't possible. Integer literals can be at most 64 bits. To get a large biginteger, you can either convert from string, or calculate the number instead of hardcoding it. In your case calculating it with BigInteger.Pow(10, digits) is the cleanest solution.
I'm still unsure on the BigInteger handling in C#, however on the Project Euler question you refer to. You can read the number in letter by letter from a text file and convert to an int. Then do the multiplications and checks. Not elegant but it works! See http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx for syntax ref.
I'm probably really late on this, but what I did was take every number and make it a separate object within an array. I then took the first 5 numbers of the array and multiplied them together and set them to a variable. If they were greater than the max, I set it to the max. I then went on to the next set for numbers 1-6 and did the same etc. I did get an out of range exception. In which case you use a try and get format until you receive this exception. If you want to see the code, I will edit my response, but to save you time on the array, if you still want to attempt this, I will give you the array. long[] a; a = new long[] { 7,3,1,6,7,1,7,6,5,3,1,3,3,0,6,2,4,9,1,9,2,2,5,1,1,9,6,7,4,4,2,6,5,7,4,7,4,2,3,5,5,3,4,9,1,9,4,9,3,4, 9,6,9,8,3,5,2,0,3,1,2,7,7,4,5,0,6,3,2,6,2,3,9,5,7,8,3,1,8,0,1,6,9,8,4,8,0,1,8,6,9,4,7,8,8,5,1,8,4,3, 8,5,8,6,1,5,6,0,7,8,9,1,1,2,9,4,9,4,9,5,4,5,9,5,0,1,7,3,7,9,5,8,3,3,1,9,5,2,8,5,3,2,0,8,8,0,5,5,1,1, 1,2,5,4,0,6,9,8,7,4,7,1,5,8,5,2,3,8,6,3,0,5,0,7,1,5,6,9,3,2,9,0,9,6,3,2,9,5,2,2,7,4,4,3,0,4,3,5,5,7, 6,6,8,9,6,6,4,8,9,5,0,4,4,5,2,4,4,5,2,3,1,6,1,7,3,1,8,5,6,4,0,3,0,9,8,7,1,1,1,2,1,7,2,2,3,8,3,1,1,3, 6,2,2,2,9,8,9,3,4,2,3,3,8,0,3,0,8,1,3,5,3,3,6,2,7,6,6,1,4,2,8,2,8,0,6,4,4,4,4,8,6,6,4,5,2,3,8,7,4,9, 3,0,3,5,8,9,0,7,2,9,6,2,9,0,4,9,1,5,6,0,4,4,0,7,7,2,3,9,0,7,1,3,8,1,0,5,1,5,8,5,9,3,0,7,9,6,0,8,6,6, 7,0,1,7,2,4,2,7,1,2,1,8,8,3,9,9,8,7,9,7,9,0,8,7,9,2,2,7,4,9,2,1,9,0,1,6,9,9,7,2,0,8,8,8,0,9,3,7,7,6, 6,5,7,2,7,3,3,3,0,0,1,0,5,3,3,6,7,8,8,1,2,2,0,2,3,5,4,2,1,8,0,9,7,5,1,2,5,4,5,4,0,5,9,4,7,5,2,2,4,3, 5,2,5,8,4,9,0,7,7,1,1,6,7,0,5,5,6,0,1,3,6,0,4,8,3,9,5,8,6,4,4,6,7,0,6,3,2,4,4,1,5,7,2,2,1,5,5,3,9,7, 5,3,6,9,7,8,1,7,9,7,7,8,4,6,1,7,4,0,6,4,9,5,5,1,4,9,2,9,0,8,6,2,5,6,9,3,2,1,9,7,8,4,6,8,6,2,2,4,8,2, 8,3,9,7,2,2,4,1,3,7,5,6,5,7,0,5,6,0,5,7,4,9,0,2,6,1,4,0,7,9,7,2,9,6,8,6,5,2,4,1,4,5,3,5,1,0,0,4,7,4, 8,2,1,6,6,3,7,0,4,8,4,4,0,3,1,9,9,8,9,0,0,0,8,8,9,5,2,4,3,4,5,0,6,5,8,5,4,1,2,2,7,5,8,8,6,6,6,8,8,1, 1,6,4,2,7,1,7,1,4,7,9,9,2,4,4,4,2,9,2,8,2,3,0,8,6,3,4,6,5,6,7,4,8,1,3,9,1,9,1,2,3,1,6,2,8,2,4,5,8,6, 1,7,8,6,6,4,5,8,3,5,9,1,2,4,5,6,6,5,2,9,4,7,6,5,4,5,6,8,2,8,4,8,9,1,2,8,8,3,1,4,2,6,0,7,6,9,0,0,4,2, 2,4,2,1,9,0,2,2,6,7,1,0,5,5,6,2,6,3,2,1,1,1,1,1,0,9,3,7,0,5,4,4,2,1,7,5,0,6,9,4,1,6,5,8,9,6,0,4,0,8, 0,7,1,9,8,4,0,3,8,5,0,9,6,2,4,5,5,4,4,4,3,6,2,9,8,1,2,3,0,9,8,7,8,7,9,9,2,7,2,4,4,2,8,4,9,0,9,1,8,8, 8,4,5,8,0,1,5,6,1,6,6,0,9,7,9,1,9,1,3,3,8,7,5,4,9,9,2,0,0,5,2,4,0,6,3,6,8,9,9,1,2,5,6,0,7,1,7,6,0,6, 0,5,8,8,6,1,1,6,4,6,7,1,0,9,4,0,5,0,7,7,5,4,1,0,0,2,2,5,6,9,8,3,1,5,5,2,0,0,0,5,5,9,3,5,7,2,9,7,2,5, 7,1,6,3,6,2,6,9,5,6,1,8,8,2,6,7,0,4,2,8,2,5,2,4,8,3,6,0,0,8,2,3,2,5,7,5,3,0,4,2,0,7,5,2,9,6,3,4,5,0 };
Performing Math operations on decimal datatype in C#?
I was wondering if the above was at all possible. For example: Math.Sqrt(myVariableHere); When looking at the overload, it requires a double parameter, so I'm not sure if there is another way to replicate this with decimal datatypes.
I don't understand why all the answers to that question are the same. There are several ways to calculate the square root from a number. One of them was proposed by Isaac Newton. I'll only write one of the simplest implementations of this method. I use it to improve the accuracy of double's square root. // x - a number, from which we need to calculate the square root // epsilon - an accuracy of calculation of the root from our number. // The result of the calculations will differ from an actual value // of the root on less than epslion. public static decimal Sqrt(decimal x, decimal epsilon = 0.0M) { if (x < 0) throw new OverflowException("Cannot calculate square root from a negative number"); decimal current = (decimal)Math.Sqrt((double)x), previous; do { previous = current; if (previous == 0.0M) return 0; current = (previous + x / previous) / 2; } while (Math.Abs(previous - current) > epsilon); return current; } About speed: in the worst case (epsilon = 0 and number is decimal.MaxValue) the loop repeats less than a three times. If you want to know more, read this (Hacker's Delight by Henry S. Warren, Jr.)
I just came across this question, and I'd suggest a different algorithm than the one SLenik proposed. This is based on the Babylonian Method. public static decimal Sqrt(decimal x, decimal? guess = null) { var ourGuess = guess.GetValueOrDefault(x / 2m); var result = x / ourGuess; var average = (ourGuess + result) / 2m; if (average == ourGuess) // This checks for the maximum precision possible with a decimal. return average; else return Sqrt(x, average); } It doesn't require using the existing Sqrt function, and thus avoids converting to double and back, with the accompanying loss of precision.
In most cases involving a decimal (currency etc), it isn't useful to take a root; and the root won't have anything like the expected precision that you might expect a decimal to have. You can of course force it by casting (assuming we aren't dealing with extreme ends of the decimal range): decimal root = (decimal)Math.Sqrt((double)myVariableHere); which forces you to at least acknowledge the inherent rounding issues.
Simple: Cast your decimal to a double and call the function, get the result and cast that back to a decimal. That will probably be faster than any sqrt function you could make on your own, and save a lot of effort.
Math.Sqrt((double)myVariableHere); Will give you back a double that's the square root of your decimal myVariableHere.
Comparing double values in C#
I've a double variable called x. In the code, x gets assigned a value of 0.1 and I check it in an 'if' statement comparing x and 0.1 if (x==0.1) { ---- } Unfortunately it does not enter the if statement Should I use Double or double? What's the reason behind this? Can you suggest a solution for this?
It's a standard problem due to how the computer stores floating point values. Search here for "floating point problem" and you'll find tons of information. In short – a float/double can't store 0.1 precisely. It will always be a little off. You can try using the decimal type which stores numbers in decimal notation. Thus 0.1 will be representable precisely. You wanted to know the reason: Float/double are stored as binary fractions, not decimal fractions. To illustrate: 12.34 in decimal notation (what we use) means 1 * 101 + 2 * 100 + 3 * 10-1 + 4 * 10-2 The computer stores floating point numbers in the same way, except it uses base 2: 10.01 means 1 * 21 + 0 * 20 + 0 * 2-1 + 1 * 2-2 Now, you probably know that there are some numbers that cannot be represented fully with our decimal notation. For example, 1/3 in decimal notation is 0.3333333…. The same thing happens in binary notation, except that the numbers that cannot be represented precisely are different. Among them is the number 1/10. In binary notation that is 0.000110011001100…. Since the binary notation cannot store it precisely, it is stored in a rounded-off way. Hence your problem.
double and Double are the same (double is an alias for Double) and can be used interchangeably. The problem with comparing a double with another value is that doubles are approximate values, not exact values. So when you set x to 0.1 it may in reality be stored as 0.100000001 or something like that. Instead of checking for equality, you should check that the difference is less than a defined minimum difference (tolerance). Something like: if (Math.Abs(x - 0.1) < 0.0000001) { ... }
You need a combination of Math.Abs on X-Y and a value to compare with. You can use following Extension method approach public static class DoubleExtensions { const double _3 = 0.001; const double _4 = 0.0001; const double _5 = 0.00001; const double _6 = 0.000001; const double _7 = 0.0000001; public static bool Equals3DigitPrecision(this double left, double right) { return Math.Abs(left - right) < _3; } public static bool Equals4DigitPrecision(this double left, double right) { return Math.Abs(left - right) < _4; } ... Since you rarely call methods on double except ToString I believe its pretty safe extension. Then you can compare x and y like if(x.Equals4DigitPrecision(y))
Comparing floating point number can't always be done precisely because of rounding. To compare (x == .1) the computer really compares (x - .1) vs 0 Result of sybtraction can not always be represeted precisely because of how floating point number are represented on the machine. Therefore you get some nonzero value and the condition evaluates to false. To overcome this compare Math.Abs(x- .1) vs some very small threshold ( like 1E-9)
From the documentation: Precision in Comparisons The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the Double value .3333 and the Double returned by dividing 1 by 3 are unequal. ... Rather than comparing for equality, one recommended technique involves defining an acceptable margin of difference between two values (such as .01% of one of the values). If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be due to differences in precision and, therefore, the values are likely to be equal. The following example uses this technique to compare .33333 and 1/3, the two Double values that the previous code example found to be unequal. So if you really need a double, you should use the techique described on the documentation. If you can, change it to a decimal. It' will be slower, but you won't have this type of problem.
Use decimal. It doesn't have this "problem".
Exact comparison of floating point values is know to not always work due to the rounding and internal representation issue. Try imprecise comparison: if (x >= 0.099 && x <= 0.101) { } The other alternative is to use the decimal data type.
double (lowercase) is just an alias for System.Double, so they are identical. For the reason, see Binary floating point and .NET. In short: a double is not an exact type and a minute difference between "x" and "0.1" will throw it off.
Double (called float in some languages) is fraut with problems due to rounding issues, it's good only if you need approximate values. The Decimal data type does what you want. For reference decimal and Decimal are the same in .NET C#, as are the double and Double types, they both refer to the same type (decimal and double are very different though, as you've seen). Beware that the Decimal data type has some costs associated with it, so use it with caution if you're looking at loops etc.
Official MS help, especially interested "Precision in Comparisons" part in context of the question. https://learn.microsoft.com/en-us/dotnet/api/system.double.equals // Initialize two doubles with apparently identical values double double1 = .333333; double double2 = (double) 1/3; // Define the tolerance for variation in their values double difference = Math.Abs(double1 * .00001); // Compare the values // The output to the console indicates that the two values are equal if (Math.Abs(double1 - double2) <= difference) Console.WriteLine("double1 and double2 are equal."); else Console.WriteLine("double1 and double2 are unequal.");
1) Should i use Double or double??? Double and double is the same thing. double is just a C# keyword working as alias for the class System.Double The most common thing is to use the aliases! The same for string (System.String), int(System.Int32) Also see Built-In Types Table (C# Reference)
Taking a tip from the Java code base, try using .CompareTo and test for the zero comparison. This assumes the .CompareTo function takes in to account floating point equality in an accurate manner. For instance, System.Math.PI.CompareTo(System.Math.PI) == 0 This predicate should return true.
// number of digits to be compared public int n = 12 // n+1 because b/a tends to 1 with n leading digits public double MyEpsilon { get; } = Math.Pow(10, -(n+1)); public bool IsEqual(double a, double b) { // Avoiding division by zero if (Math.Abs(a)<= double.Epsilon || Math.Abs(b) <= double.Epsilon) return Math.Abs(a - b) <= double.Epsilon; // Comparison return Math.Abs(1.0 - a / b) <= MyEpsilon; } Explanation The main comparison function done using division a/b which should go toward 1. But why division? it simply puts one number as reference defines the second one. For example a = 0.00000012345 b = 0.00000012346 a/b = 0.999919002 b/a = 1.000081004 (a/b)-1 = 8.099789405475458e-5 1-(b/a) = 8.100445524503848e-5 or a=12345*10^8 b=12346*10^8 a/b = 0.999919002 b/a = 1.000081004 (a/b)-1 = 8.099789405475458e-5 1-(b/a) = 8.100445524503848e-5 by division we get rid of trailing or leading zeros (or relatively small numbers) that pollute our judgement of number precision. In the example, the comparison is of order 10^-5, and we have 4 number accuracy, because of that in the beginning code I wrote comparison with 10^(n+1) where n is number accuracy.
Adding onto Valentin Kuzub's answer above: we could use a single method that supports providing nth precision number: public static bool EqualsNthDigitPrecision(this double value, double compareTo, int precisionPoint) => Math.Abs(value - compareTo) < Math.Pow(10, -Math.Abs(precisionPoint)); Note: This method is built for simplicity without added bulk and not with performance in mind.
As a general rule: Double representation is good enough in most cases but can miserably fail in some situations. Use decimal values if you need complete precision (as in financial applications). Most problems with doubles doesn't come from direct comparison, it use to be a result of the accumulation of several math operations which exponentially disturb the value due to rounding and fractional errors (especially with multiplications and divisions). Check your logic, if the code is: x = 0.1 if (x == 0.1) it should not fail, it's to simple to fail, if X value is calculated by more complex means or operations it's quite possible the ToString method used by the debugger is using an smart rounding, maybe you can do the same (if that's too risky go back to using decimal): if (x.ToString() == "0.1")
Floating point number representations are notoriously inaccurate because of the way floats are stored internally. E.g. x may actually be 0.0999999999 or 0.100000001 and your condition will fail. If you want to determine if floats are equal you need to specify whether they're equal to within a certain tolerance. I.e.: if(Math.Abs(x - 0.1) < tol) { // Do something }
My extensions method for double comparison: public static bool IsEqual(this double value1, double value2, int precision = 2) { var dif = Math.Abs(Math.Round(value1, precision) - Math.Round(value2, precision)); while (precision > 0) { dif *= 10; precision--; } return dif < 1; }
To compare floating point, double or float types, use the specific method of CSharp: if (double1.CompareTo(double2) > 0) { // double1 is greater than double2 } if (double1.CompareTo(double2) < 0) { // double1 is less than double2 } if (double1.CompareTo(double2) == 0) { // double1 equals double2 } https://learn.microsoft.com/en-us/dotnet/api/system.double.compareto?view=netcore-3.1
How can I ensure that a division of integers is always rounded up?
I want to ensure that a division of integers is always rounded up if necessary. Is there a better way than this? There is a lot of casting going on. :-) (int)Math.Ceiling((double)myInt1 / myInt2)
UPDATE: This question was the subject of my blog in January 2013. Thanks for the great question! Getting integer arithmetic correct is hard. As has been demonstrated amply thus far, the moment you try to do a "clever" trick, odds are good that you've made a mistake. And when a flaw is found, changing the code to fix the flaw without considering whether the fix breaks something else is not a good problem-solving technique. So far we've had I think five different incorrect integer arithmetic solutions to this completely not-particularly-difficult problem posted. The right way to approach integer arithmetic problems -- that is, the way that increases the likelihood of getting the answer right the first time - is to approach the problem carefully, solve it one step at a time, and use good engineering principles in doing so. Start by reading the specification for what you're trying to replace. The specification for integer division clearly states: The division rounds the result towards zero The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs If the left operand is the smallest representable int and the right operand is –1, an overflow occurs. [...] it is implementation-defined as to whether [an ArithmeticException] is thrown or the overflow goes unreported with the resulting value being that of the left operand. If the value of the right operand is zero, a System.DivideByZeroException is thrown. What we want is an integer division function which computes the quotient but rounds the result always upwards, not always towards zero. So write a specification for that function. Our function int DivRoundUp(int dividend, int divisor) must have behaviour defined for every possible input. That undefined behaviour is deeply worrying, so let's eliminate it. We'll say that our operation has this specification: operation throws if divisor is zero operation throws if dividend is int.minval and divisor is -1 if there is no remainder -- division is 'even' -- then the return value is the integral quotient Otherwise it returns the smallest integer that is greater than the quotient, that is, it always rounds up. Now we have a specification, so we know we can come up with a testable design. Suppose we add an additional design criterion that the problem be solved solely with integer arithmetic, rather than computing the quotient as a double, since the "double" solution has been explicitly rejected in the problem statement. So what must we compute? Clearly, to meet our spec while remaining solely in integer arithmetic, we need to know three facts. First, what was the integer quotient? Second, was the division free of remainder? And third, if not, was the integer quotient computed by rounding up or down? Now that we have a specification and a design, we can start writing code. public static int DivRoundUp(int dividend, int divisor) { if (divisor == 0 ) throw ... if (divisor == -1 && dividend == Int32.MinValue) throw ... int roundedTowardsZeroQuotient = dividend / divisor; bool dividedEvenly = (dividend % divisor) == 0; if (dividedEvenly) return roundedTowardsZeroQuotient; // At this point we know that divisor was not zero // (because we would have thrown) and we know that // dividend was not zero (because there would have been no remainder) // Therefore both are non-zero. Either they are of the same sign, // or opposite signs. If they're of opposite sign then we rounded // UP towards zero so we're done. If they're of the same sign then // we rounded DOWN towards zero, so we need to add one. bool wasRoundedDown = ((divisor > 0) == (dividend > 0)); if (wasRoundedDown) return roundedTowardsZeroQuotient + 1; else return roundedTowardsZeroQuotient; } Is this clever? No. Beautiful? No. Short? No. Correct according to the specification? I believe so, but I have not fully tested it. It looks pretty good though. We're professionals here; use good engineering practices. Research your tools, specify the desired behaviour, consider error cases first, and write the code to emphasize its obvious correctness. And when you find a bug, consider whether your algorithm is deeply flawed to begin with before you just randomly start swapping the directions of comparisons around and break stuff that already works.
All the answers here so far seem rather over-complicated. In C# and Java, for positive dividend and divisor, you simply need to do: ( dividend + divisor - 1 ) / divisor Source: Number Conversion, Roland Backhouse, 2001
The final int-based answer For signed integers: int div = a / b; if (((a ^ b) >= 0) && (a % b != 0)) div++; For unsigned integers: int div = a / b; if (a % b != 0) div++; The reasoning for this answer Integer division '/' is defined to round towards zero (7.7.2 of the spec), but we want to round up. This means that negative answers are already rounded correctly, but positive answers need to be adjusted. Non-zero positive answers are easy to detect, but answer zero is a little trickier, since that can be either the rounding up of a negative value or the rounding down of a positive one. The safest bet is to detect when the answer should be positive by checking that the signs of both integers are identical. Integer xor operator '^' on the two values will result in a 0 sign-bit when this is the case, meaning a non-negative result, so the check (a ^ b) >= 0 determines that the result should have been positive before rounding. Also note that for unsigned integers, every answer is obviously positive, so this check can be omitted. The only check remaining is then whether any rounding has occurred, for which a % b != 0 will do the job. Lessons learned Arithmetic (integer or otherwise) isn't nearly as simple as it seems. Thinking carefully required at all times. Also, although my final answer is perhaps not as 'simple' or 'obvious' or perhaps even 'fast' as the floating point answers, it has one very strong redeeming quality for me; I have now reasoned through the answer, so I am actually certain it is correct (until someone smarter tells me otherwise -furtive glance in Eric's direction-). To get the same feeling of certainty about the floating point answer, I'd have to do more (and possibly more complicated) thinking about whether there is any conditions under which the floating-point precision might get in the way, and whether Math.Ceiling perhaps does something undesirable on 'just the right' inputs. The path travelled Replace (note I replaced the second myInt1 with myInt2, assuming that was what you meant): (int)Math.Ceiling((double)myInt1 / myInt2) with: (myInt1 - 1 + myInt2) / myInt2 The only caveat being that if myInt1 - 1 + myInt2 overflows the integer type you are using, you might not get what you expect. Reason this is wrong: -1000000 and 3999 should give -250, this gives -249 EDIT: Considering this has the same error as the other integer solution for negative myInt1 values, it might be easier to do something like: int rem; int div = Math.DivRem(myInt1, myInt2, out rem); if (rem > 0) div++; That should give the correct result in div using only integer operations. Reason this is wrong: -1 and -5 should give 1, this gives 0 EDIT (once more, with feeling): The division operator rounds towards zero; for negative results this is exactly right, so only non-negative results need adjustment. Also considering that DivRem just does a / and a % anyway, let's skip the call (and start with the easy comparison to avoid modulo calculation when it is not needed): int div = myInt1 / myInt2; if ((div >= 0) && (myInt1 % myInt2 != 0)) div++; Reason this is wrong: -1 and 5 should give 0, this gives 1 (In my own defence of the last attempt I should never have attempted a reasoned answer while my mind was telling me I was 2 hours late for sleep)
Perfect chance to use an extension method: public static class Int32Methods { public static int DivideByAndRoundUp(this int number, int divideBy) { return (int)Math.Ceiling((float)number / (float)divideBy); } } This makes your code uber readable too: int result = myInt.DivideByAndRoundUp(4);
You could write a helper. static int DivideRoundUp(int p1, int p2) { return (int)Math.Ceiling((double)p1 / p2); }
You could use something like the following. a / b + ((Math.Sign(a) * Math.Sign(b) > 0) && (a % b != 0)) ? 1 : 0)
For signed or unsigned integers. q = x / y + !(((x < 0) != (y < 0)) || !(x % y)); For signed dividends and unsigned divisors. q = x / y + !((x < 0) || !(x % y)); For unsigned dividends and signed divisors. q = x / y + !((y < 0) || !(x % y)); For unsigned integers. q = x / y + !!(x % y); Zero divisor fails (as with a native operation). Cannot overflow. Elegant and correct. The key to understanding the behavior is to recognize the difference in truncated, floored and ceilinged division. C#/C++ is natively truncated. When the quotient is negative (i.e. the operators signs are different) then truncation is a ceiling (less negative). Otherwise truncation is a floor (less positive). So, if there is a remainder, add 1 if the result is positive. Modulo is the same, but you instead add the divisor. Flooring is the same, but you subtract under the reversed conditions.
By round up, I take it you mean away form zero always. Without any castings, use the Math.DivRem() function /// <summary> /// Divide a/b but always round up /// </summary> /// <param name="a">The numerator.</param> /// <param name="b">The denominator.</param> int DivRndUp(int a, int b) { // remove sign int s = Math.Sign(a) * Math.Sign(b); a = Math.Abs(a); b = Math.Abs(b); var c = Math.DivRem(a, b, out int r); // if remainder >0 round up if (r > 0) { c++; } return s * c; } If roundup means always up regardless of sign, then /// <summary> /// Divide a/b but always round up /// </summary> /// <param name="a">The numerator.</param> /// <param name="b">The denominator.</param> int DivRndUp(int a, int b) { // remove sign int s = Math.Sign(a) * Math.Sign(b); a = Math.Abs(a); b = Math.Abs(b); var c = Math.DivRem(a, b, out int r); // if remainder >0 round up if (r > 0) { c+=s; } return s * c; }
Some of the above answers use floats, this is inefficient and really not necessary. For unsigned ints this is an efficient answer for int1/int2: (int1 == 0) ? 0 : (int1 - 1) / int2 + 1; For signed ints this will not be correct
The problem with all the solutions here is either that they need a cast or they have a numerical problem. Casting to float or double is always an option, but we can do better. When you use the code of the answer from #jerryjvl int div = myInt1 / myInt2; if ((div >= 0) && (myInt1 % myInt2 != 0)) div++; there is a rounding error. 1 / 5 would round up, because 1 % 5 != 0. But this is wrong, because rounding will only occur if you replace the 1 with a 3, so the result is 0.6. We need to find a way to round up when the calculation give us a value greater than or equal to 0.5. The result of the modulo operator in the upper example has a range from 0 to myInt2-1. The rounding will only occur if the remainder is greater than 50% of the divisor. So the adjusted code looks like this: int div = myInt1 / myInt2; if (myInt1 % myInt2 >= myInt2 / 2) div++; Of course we have a rounding problem at myInt2 / 2 too, but this result will give you a better rounding solution than the other ones on this site.