How to recursively determine quotient in prolog with limited predicates? - recursion

So I have been trying to determine a quotient of integers in prolog by only using build in predicates "is", "*", "+" and "-". It expects the quotient to be an integer so I don't need any decimals or rest.
I quickly came up with a solution but for some reason it just won't work as intended. It keeps giving me the same error and I just can't figure out what I am doing wrong. I am new to prolog btw. and due to university I have to look into it.
Here is what I am trying:
div(0, 0, _).
div(1, Dividend, Dividend).
div(Quotient, Dividend, Divisor) :-
NewDividend is Dividend - Divisor,
div(NewQuotient, NewDividend , Divisor),
NewQuotient + 1 is Quotient.
I have basically tried anything from swapping stuff around to adding more predicates such as "div(Dividend, Dividend, 1).".
Here is what I shows when I type div(Y, 15, 3).
ERROR: Arguments are not sufficiently instantiated
ERROR: In:
ERROR: [13] 0+1 is _2768
ERROR: [12] div(_2798,3,3) at div.pl:63
ERROR: [11] div(_2826,6,3) at div.pl:63
ERROR: [10] div(_2854,9,3) at div.pl:63
ERROR: [9] div(_2882,12,3) at div.pl:63
ERROR: [8] div(_2910,15,3) at div.pl:63
ERROR: [7] <user>
I kinda understand what the errors want to tell me but I just don't get why it won't work as I expect it to work. It gets that the quotient is 0 if dividend is 0 and from there on it should just add 1s until it is back at the first call but it won't. I have to use this signature for my predicate by the way. It is an assignment from the university.
Any help is appreciated!

I found the solution myself:
div(0,0,_).
div(Quotient, Dividend, Divisor) :-
Rest is Dividend - Divisor,
div(NewQuotient, Rest, Divisor),
Quotient is NewQuotient + 1.

Related

What does the “>>” operator in C# do?

I ran into this statement in a piece of code:
Int32 medianIndex = colorList.Count >> 1;
colorList is a list of class System.Drawing.Color.
Now the statement is supposed to retrieve the median index of the list .. like the half point of it .. but I can't understand how that >> symbol works and how the "1" is supposed to give the median index .. I would appreciate some help :S
The >> operator performs a bit shift.
The expression >> 1 is almost* the same as / 2 so the programmer was calculating the index colorList.Count / 2 which is** the median. To understand why this is the case you need to look at the binary representation of the numbers involved. For example if you have 25 elements in your list:
n : 0 0 0 1 1 0 0 1 = 25
\ \ \ \ \ \ \
n >> 1: 0 0 0 0 1 1 0 0 = 12
In general using a bitwise operator when really you want to perform a division is a bad practice. It is probably a premature optimization made because the programmer thought it would be faster to perform a bitwise operation instead of a division. It would be much clearer to write a division and I wouldn't be surprised if the performance of the two approaches is comparable.
*The expression x >> 1 gives the same result as x / 2 for all positive integers and all negative even integers. However it gives a different result for negative odd integers. For example -101 >> 1 == -51 whereas -101 / 2 == -50.
**Actually the median is only defined this way if the list has an odd number of elements. For an even number of elements this method will strictly speaking not give the median.
It's a bitwise opperator a definition i just grabbed from http://en.wikibooks.org/wiki/C_Sharp_Programming/Operators:
The binary operator >> evaluates its operands and returns the resulting first argument right-shifted by the number of bits specified by the second argument. It discards low-order bits that are shifted beyond the size of its first argument and sets new high-order bits to the sign bit of the first argument, or to zero if the first argument is unsigned.
Its basically dividing by 2...
>> is the bitwise right-shift operator, and shifting colorList.Count to the right by 1 is more or less equivalent to colorList.Count / 2.
A right shift of a >> b can be defined as a / 2 ^ b.
As for why you would use a right-shift rather than divide by 2, I have no idea.
C programmers (of which I've been one for over 20 years) routinely have used bitwise shifts for multiplying or dividing by powers of 2. The reason was that in older architectures (think 2 MHz processor, 32K of memory, and no disk) it was significantly faster to shift and generally compiled to a single machine instruction. Even though I write primarily C# now, I still, as a mater of habit, sometimes use this trick. Another common C convention that most C# programmers have never seen is having an assignment embedded within a conditional. For example:
if ( (a = getmeanumber()) == 0 )
/* do something */ ;
Anyway, as to the original question and the reasons for its use, they largely no longer exist except with the limited realm of embedded programming where every byte and clock cycle could matter.
It's not very readable code, basically it just divides the number by 2.
>> is the shift-right operator, shifting all bits one position to the right.
0110 (6) becomes 0011 (3)

C# Decimal To Octal

There have been many questions but i can't seem to find the why in the answers. It's usually: no, replace this with this or this should work.
My task is to create a program that asks the user to input a 3 digit positive integer (decimal) that converts it to octal.
For example, on paper: To convert the number 112 to octal. (8 is the base number for octal.)
These are the steps you would take:
112 / 8 = 14 remainder = 0
14 / 8 = 1 remainder = 6
1 / 8 = 0 remainder = 1
Remainder from bottom to up is the octal number that represents 112 in decimal.
So the octal number for 112 is 160.
I found the following program on the internet but i don't understand it fully.
The comments in the program are mine. Could anyone explain it to me please?
//declaration and initialization of variables but why is there an array?
int decimalNumber, quotient, i = 1, j;
int[] octalNumber = new int[100];
//input
Console.WriteLine("Enter a Decimal Number :");
decimalNumber = int.Parse(Console.ReadLine());
quotient = decimalNumber;
//as long as quotient is not equal to 0, statement will run
while (quotient != 0)
{
//this is how the remainder is calculated but it is then put in an array + 1, i don't understand this.
octalNumber[i++] = quotient % 8;
//divide the number given by the user with the octal base number
quotient = quotient / 8;
}
Console.Write("Equivalent Octal Number is ");
//i don't understand the code below here aswell.
for (j = i - 1; j > 0; j--)
Console.Write(octalNumber[j]);
Console.Read();
Any help is truly appreciated.
This is already built into .NET, Convert.ToString already does this.
In your code, just after you have decimalNumber = int.Parse(...) you can do this:
Console.WriteLine(Convert.ToString(decimalNumber, 8));
Console.Read();
and then remove the rest of the code.
Now, if you're not asking how to do octal conversion in .NET but actually how that code works, here's how it works:
This loop does the heavy lifting:
1 while (quotient != 0)
{
//this is how the remainder is calculated but it is then put in an array + 1, i don't understand this.
2 octalNumber[i++] = quotient % 8;
//divide the number given by the user with the octal base number
3 quotient = quotient / 8;
}
I added some numbers to the lines to make it easier writing a description.
Basically, the loop does this (lines above correspond to points below).
As long as we have a number to convert (ie. we're still not done), loop.
Figure out the least significant digit, this is the remainder after dividing by 8, which is handled by the remainder operator, %, store this digit into the array in the next position.
Divide by 8 to get rid of that least significant digit and move all the other digits one up
Then loop back.
However, since we essentially found all the digits from the rightmost side towards the left, the loop at the end writes them back out in their opposite order.
As an exercise to the reader, try to figure out how the code in the question behaves if you:
Input a negative number
Input 0
(hint, it doesn't behave correctly but Convert.ToString does)
The first thing to understand is: this is a terrible way to solve this problem. The code is full of odd choices; it looks like someone took a bad C solution of this problem and translated it to C# without applying careful thought or using good practices. If you are trying to learn how to understand crappy code you find on the internet, this is a great example. If you are trying to learn how to design good code, this is a great example of what not to do.
//declaration and initialization of variables but why is there an array?
There's an array because we wish to store all the octal digits, and an array is a convenient mechanism for storing a number of data of the same type.
But we could ask some more pertinent questions here:
Why of size 100? It's not wrong, but that's enormously larger than necessary. What thought process led to 100 being chosen? Why wasn't that thought process documented anywhere?
Why an array of int? We're outputting text, which is a sequence of chars. It would seem more natural to have a bunch of chars.
Why an array? Since we are building a first-in-last-out data structure, a stack seems more appropriate. Or why not simply accumulate a string? That's inefficient if the string is large, but an octal string from a 32 bit integer is never large!
Why does the program produce output to the console? Surely a better factored program would have a method that takes an int and returns an octal string, which can then be printed.
Why do some of the variables have descriptive names and some have undescriptive names? Is the author of the code deliberately trying to confuse the reader? Or did they simply not think about it very carefully?
Why does i - apparently the current index into the array -- start at one?! This is simply bizarre. Arrays start at zero in C#.
What happens if you type in a negative number? Try it!
What happens if you type in zero?
We then go on to:
decimalNumber = int.Parse(Console.ReadLine());
This code presumes that the typed-in text is a legal integer, which is not guaranteed. So this program can crash. TryParse should be used, and the failure mode should be handled.
// this is how the remainder is calculated but it is
// then put in an array + 1, i don't understand this.
octalNumber[i++] = quotient % 8;
The author of the code thinks they are being clever. This is too much cleverness. Rewrite the code in your head to how it should have been implemented in the first place. First, rename i to currentIndex. Next, produce one side effect per statement, not two:
while (quotient != 0)
{
octalNumber[currentIndex] = quotient % 8;
currentIndex += 1;
quotient = quotient / 8;
}
Now it should be clear what is going on.
// I don't understand the code below here as well.
for (j = i - 1; j > 0; j--)
Console.Write(octalNumber[j]);
Do a little example. Suppose the number is 14, which is 16 in octal. First time through the loop we put 6 in slot 1. Next time through, we put 1 in slot 2. So the array is {0, 6, 1, 0, 0, 0, 0 ... } and i is 3. We wish to output 16. So we loop j from i-1 to 1, and print out 1 then 6.
So, exercise for you: write this program again, this time using the conventions of a well-designed C# program. Put your attempt on the code review site and people will be happy to give you tips on how to improve it.
An array is used because they are calculating each digit every interation of the while loop. (e.g.) {0, 6, 1}
The last part of the program is printing each digit out, starting with the last item in the array and moving to the first. in this case it would print out:
160

Ambiguous call Math.Round ( int64 / int64, int)

I would like to do percentage with large number (int64 : 600 851 475 143)
My actual operation is
a = Math.round(i / 600851475143 * 100, 5);
With i also an int64 between 1 and 600851475143. The result will be between 0,00000% and 100,00000% if i'm right.
But Visual Studio Express 2013 say me that ambiguous call between methods 'System.Math.Round(decimal, int)' and 'System.Math.Round(double, int)'.
How to say to visual that the good methods is System.Math.Round(decimal, int) even if some int64 are in the operation ?
Bonus :
To understand my problem, i'm trying to solve ProjectEuler.net's problem 3 :
"The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?"
I did my method and it works with 13195. But now i have to do it with 600851475143 (on x64 system), but my algo seems not to be optimezed and i would like to add an percentage progress bar to know if my EXE crash or not. My a var is this percentage...
I DON'T WANT THE ANSWER of Euleur problem 3, i just need to fix my percentage issue...
Marking the numeric value with an M after it will make it a decimal value. And use the correct overload for Round.
var a = Math.Round(i / 600851475143M * 100, 5);
If i is an integer then the quotient is zero or one, because an integer divided by an integer is always an integer in C#. You meant to say
a = Math.round(i / 600851475143.0 * 100.0, 5);
Which forces the calculation to be in doubles, or
a = Math.round(i / 600851475143.0m * 100.0m, 5);
Which forces it to be in decimals.
The error message is correct -- it is ambiguous whether the integer result should be converted to decimal or double. It's just not pointing out the more fundamental error.
Incidentally, this error is extremely common. So common in fact that my team is working on a static analyzer to detect it. A now-deleted answer actually gave a form of the error that I see quite frequently:
a = Math.round((decimal)(i / 600851475143 * 100), 5);
That removes the ambiguity -- clearly you meant the decimal overload -- but the calculation is done in integers, rounded to integers, and then converted to decimal! If you're going to put in a cast it has to be on one of the operands, not on the result.

Fixed-point modulo edge cases

I'm implementing a Q31.32 fixed-point numeric type based on System.Int64 in C#. Right now I'm trying to get the modulo operation correctly (%).
All implementations of fixed-point arithmetic I've seen define Qm.n modulo simply in terms of integer modulo, i.e. the modulo of two Qm.n numbers is the modulo of their underlying integer representation. This works in the general case but fails in two specific cases:
x % y throws an OverflowException if x == Int64.MinValue and y == -1.
I can easily deal with this with an if statement and returning 0 in
this case, although this is strange behavior (and unchecked is of no help here).
x % y incorrectly returns 0 for some small values of x and y. For
example, if the integer representations of x and y are -413 and 59
(decimal: ~-0.000000096159 and ~0,000000013737), the modulo is 0
(decimal: 0) while the modulo of their decimal value is (according to System.Decimal)
~-0.000000013737. This error is about 60 times greater than the
maximum precision of the type (2^-32), so it cannot be considered a
rounding error.
What is the cause of this last error and is there anything I can do to obtain better accuracy?
I found out the problem.
-413 % 59 = 0 is correct !!!
because -7 * 59 = -413
Your assumed correct result is mostly probable taken from 2s complement of -413 which leads to confusion.
[edit 1]
At Asik's suggestion I use calculator and my last comment to his question was right. The problem is in his print accuracy and not on above 2s complement or modulo see this:
413 >> 32 = 0.00000009615905582904815673828125
59 >> 32 = 0.00000001373700797557830810546875
0.00000009615905582904815673828125 / 0.00000001373700797557830810546875 = 7
0.00000009615905582904815673828125 % 0.00000001373700797557830810546875 = 0
for more info about printing numbers see this: https://stackoverflow.com/a/18401040/2521214
P.S. how exactly did you obtain result that modulo should be ~-0.000000013737 ? it is suspiciously equal to the -59>>32 ... maybe your reference can not handle signed numbers correctly (-413)<(59) and throw result of modulo simply 59 because of it (to avoid division) with signum combined from both numbers.

Get number of digits in an unsigned long integer c#

I'm trying to determine the number of digits in a c# ulong number, i'm trying to do so using some math logic rather than using ToString().Length. I have not benchmarked the 2 approaches but have seen other posts about using System.Math.Floor(System.Math.Log10(number)) + 1 to determine the number of digits.
Seems to work fine until i transition from 999999999999997 to 999999999999998 at which point, it i start getting an incorrect count.
Has anyone encountered this issue before ?
I have seen similar posts with a Java emphasis # Why log(1000)/log(10) isn't the same as log10(1000)? and also a post # How to get the separate digits of an int number? which indicates how i could possibly achieve the same using the % operator but with a lot more code
Here is the code i used to simulate this
Action<ulong> displayInfo = number =>
Console.WriteLine("{0,-20} {1,-20} {2,-20} {3,-20} {4,-20}",
number,
number.ToString().Length,
System.Math.Log10(number),
System.Math.Floor(System.Math.Log10(number)),
System.Math.Floor(System.Math.Log10(number)) + 1);
Array.ForEach(new ulong[] {
9U,
99U,
999U,
9999U,
99999U,
999999U,
9999999U,
99999999U,
999999999U,
9999999999U,
99999999999U,
999999999999U,
9999999999999U,
99999999999999U,
999999999999999U,
9999999999999999U,
99999999999999999U,
999999999999999999U,
9999999999999999999U}, displayInfo);
Array.ForEach(new ulong[] {
1U,
19U,
199U,
1999U,
19999U,
199999U,
1999999U,
19999999U,
199999999U,
1999999999U,
19999999999U,
199999999999U,
1999999999999U,
19999999999999U,
199999999999999U,
1999999999999999U,
19999999999999999U,
199999999999999999U,
1999999999999999999U
}, displayInfo);
Thanks in advance
Pat
log10 is going to involve floating point conversion - hence the rounding error. The error is pretty small for a double, but is a big deal for an exact integer!
Excluding the .ToString() method and a floating point method, then yes I think you are going to have to use an iterative method but I would use an integer divide rather than a modulo.
Integer divide by 10. Is the result>0? If so iterate around. If not, stop.
The number of digits is the number of iterations required.
Eg. 5 -> 0; 1 iteration = 1 digit.
1234 -> 123 -> 12 -> 1 -> 0; 4 iterations = 4 digits.
I would use ToString().Length unless you know this is going to be called millions of times.
"premature optimization is the root of all evil" - Donald Knuth
From the documentation:
By default, a Double value contains 15
decimal digits of precision, although
a maximum of 17 digits is maintained
internally.
I suspect that you're running into precision limits. Your value of 999,999,999,999,998 probably is at the limit of precision. And since the ulong has to be converted to double before calling Math.Log10, you see this error.
Other answers have posted why this happens.
Here is an example of a fairly quick way to determine the "length" of an integer (some cases excluded). This by itself is not very interesting -- but I include it here because using this method in conjunction with Log10 can get the accuracy "perfect" for the entire range of an unsigned long without requiring a second log invocation.
// the lookup would only be generated once
// and could be a hard-coded array literal
ulong[] lookup = Enumerable.Range(0, 20)
.Select((n) => (ulong)Math.Pow(10, n)).ToArray();
ulong x = 999;
int i = 0;
for (; i < lookup.Length; i++) {
if (lookup[i] > x) {
break;
}
}
// i is length of x "in a base-10 string"
// does not work with "0" or negative numbers
This lookup-table approach can be easily converted to any base. This method should be faster than the iterative divide-by-base approach but profiling is left as an exercise to the reader. (A direct if-then branch broken into "groups" is likely quicker yet, but that's way too much repetitive typing for my tastes.)
Happy coding.

Resources