A recursive function in VDM - formal-methods

How would I define a recursive function to find the biggest power of two less than an input number in VDM?
The function is as follows:
largest: N -> N
All I've got so far is:
largest(n) =
if n=1 then 0
else if n=2 then 1
else ... largest(...)

It would be something like "else one plus the largest of half this number". But since this looks suspiciously like an exercise, I'll let you work out the fine details.

Related

Given no modulus or if even/odd function, how would one check for an odd or even number?

I have recently sat a computing exam in university in which we were never taught beforehand about the modulus function or any other check for odd/even function and we have no access to external documentation except our previous lecture notes. Is it possible to do this without these and how?
Bitwise AND (&)
Extract the last bit of the number using the bitwise AND operator. If the last bit is 1, then it's odd, else it's even. This is the simplest and most efficient way of testing it. Examples in some languages:
C / C++ / C#
bool is_even(int value) {
return (value & 1) == 0;
}
Java
public static boolean is_even(int value) {
return (value & 1) == 0;
}
Python
def is_even(value):
return (value & 1) == 0
I assume this is only for integer numbers as the concept of odd/even eludes me for floating point values.
For these integer numbers, the check of the Least Significant Bit (LSB) as proposed by Rotem is the most straightforward method, but there are many other ways to accomplish that.
For example, you could use the integer division operation as a test. This is one of the most basic operation which is implemented in virtually every platform. The result of an integer division is always another integer. For example:
>> x = int64( 13 ) ;
>> x / 2
ans =
7
Here I cast the value 13 as a int64 to make sure MATLAB treats the number as an integer instead of double data type.
Also here the result is actually rounded towards infinity to the next integral value. This is MATLAB specific implementation, other platform might round down but it does not matter for us as the only behavior we look for is the rounding, whichever way it goes. The rounding allow us to define the following behavior:
If a number is even: Dividing it by 2 will produce an exact result, such that if we multiply this result by 2, we obtain the original number.
If a number is odd: Dividing it by 2 will result in a rounded result, such that multiplying it by 2 will yield a different number than the original input.
Now you have the logic worked out, the code is pretty straightforward:
%% sample input
x = int64(42) ;
y = int64(43) ;
%% define the checking function
% uses only multiplication and division operator, no high level function
is_even = #(x) int64(x) == (int64(x)/2)*2 ;
And obvisouly, this will yield:
>> is_even(x)
ans =
1
>> is_even(y)
ans =
0
I found out from a fellow student how to solve this simplistically with maths instead of functions.
Using (-1)^n :
If n is odd then the outcome is -1
If n is even then the outcome is 1
This is some pretty out-of-the-box thinking, but it would be the only way to solve this without previous knowledge of complex functions including mod.

Does `if` work only in combination with `else` in Series.apply(lambda x)?

I'm getting a SyntaxError for:
housing['Lot Area'].apply(lambda x: x + 50000 if x > 20000)
When I add else, the code runs fine:
housing['Lot Area'].apply(lambda x: x + 50000 if x > 20000 else x)
Does if only work in combination with else here? I'd like to increment x with 50000 only if x > 20000 -- otherwise I'd like x to remain unchanged. I find the else part a bit redundant here. Besides the first question before, is there any way to write this code without the else part?
Base on your description , even apply is not need here
housing.loc[housing['Lot Area']>20000,'Lot Area']+=50000
Comment from Alex :
if the if statement resolves to False for a value, then apply() doesn't return and just lets the value in the Series as it is
you're getting a SyntaxError because you are typing invalid syntax. the ternary operator must be used like
expression if bool else other_expression

Calculating a recursive sequence iteratively - code optimization

I have to calculate first 3000 items of a sequence given as follows:
a_1=1,
a_n+1 = smallest integer > a_n, for which for every (not necessarily different) 1<= i,j,k <= n+1 applies (a_i+a_j not equal 3*a_k)
I have written code (in Magma) that works correctly, but its time complexity is obviously way too large. I am asking if there is a way to reduce the time complexity. I had an idea to somehow move the inner for loop (which is the one causing havoc) out in a way of making an array of all the sums, but I cant get it to work right. Attaching my code below:
S:=[1];
for n:=2 to 3000 do
new:=S[n-1];
repeat
flag:=0;
new+:=1;
for i,j in S do
if (i+j eq 3*new) or (i+new eq 3*j) then
flag:=1;
break i;
end if;
end for;
until flag eq 0;
S[n]:=new;
end for;
print S[2015];
P.S.: If it helps, I also know Python, Pascal and C if you prefer any of those languages.
I copied your program in MAGMA. Run time for n=2978 was 4712.766 seconds. I changed your program as follow and result was amazing. Run time for changed version for n=3000 was 41.250 seconds.
S:=[1];
for n:=2 to 3000 do
new:=S[n-1];
repeat
flag:=0;
new+:=1;
for i in S do
if ((3*new-i) in S) or ((i+new)/3 in S) then
flag:=1;
break i;
end if;
end for;
until flag eq 0;
S[n]:=new;
end for;

Finding all combination of numbers to sum without repetition

I want to get all combination of numbers to sum.
My input is X that is variable and X is the number of numbers,
For example:
X=4 means we have 1,2,3,4
x=100 means 1,2,3,4,5,,98,99,100
Now I want to get {(1,2)(1,3)(1,4)(2,3)(2,4)(3,4),(1,2,3)(1,3,4)…}
We can’t have repetitive sequence like (1,2)(2,1)(1,2,3)(1,3,2)
I want to get all combinations that these numbers can be sum without repetitive sequence.
Can anyone help me to find it’s algorithm? I must code it in VBA of Excel using for loops
the "algorithm" is solved from Maths and given by the combinations of X by 2:
X!/((X-2)!*2!)=X!/((X-2)!*2)
(note: Just in case... "!" is the factorial...)
now if you want to use for-loop to calculate factorial (written in c):
int main()
{
int num,factorial=1;
cout<<" Enter Number To Find Its Factorial: ";
cin>>num;
for(int a=1;a<=num;a++)
{
factorial=factorial*a;
}

Weird Objective-C Mod Behavior for Negative Numbers

So I thought that negative numbers, when mod'ed should be put into positive space... I cant get this to happen in objective-c
I expect this:
-1 % 3 = 2
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
But get this
-1 % 3 = -1
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
Why is this and is there a workaround?
result = n % 3;
if( result < 0 ) result += 3;
Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.
In C and Objective-C, the division and modulus operators perform truncation towards zero. a / b is floor(a / b) if a / b > 0, otherwise it is ceiling(a / b) if a / b < 0. It is always the case that a == (a / b) * b + (a % b), unless of course b is 0. As a consequence, positive % positive == positive, positive % negative == positive, negative % positive == negative, and negative % negative == negative (you can work out the logic for all 4 cases, although it's a little tricky).
If n has a limited range, then you can get the result you want simply by adding a known constant multiple of 3 that is greater that the absolute value of the minimum.
For example, if n is limited to -1000..2000, then you can use the expression:
result = (n+1002) % 3;
Make sure the maximum plus your constant will not overflow when summed.
We have a problem of language:
math-er-says: i take this number plus that number mod other-number
code-er-hears: I add two numbers and then devide the result by other-number
code-er-says: what about negative numbers?
math-er-says: WHAT? fields mod other-number don't have a concept of negative numbers?
code-er-says: field what? ...
the math person in this conversations is talking about doing math in a circular number line. If you subtract off the bottom you wrap around to the top.
the code person is talking about an operator that calculates remainder.
In this case you want the mathematician's mod operator and have the remainder function at your disposal. you can convert the remainder operator into the mathematician's mod operator by checking to see if you fell of the bottom each time you do subtraction.
If this will be the behavior, and you know that it will be, then for m % n = r, just use r = n + r. If you're unsure of what will happen here, use then r = r % n.
Edit: To sum up, use r = ( n + ( m % n ) ) % n
I would have expected a positive number, as well, but I found this, from ISO/IEC 14882:2003 : Programming languages -- C++, 5.6.4 (found in the Wikipedia article on the modulus operation):
The binary % operator yields the remainder from the division of the first expression by the second. .... If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined
JavaScript does this, too. I've been caught by it a couple times. Think of it as a reflection around zero rather than a continuation.
Why: because that is the way the mod operator is specified in the C-standard (Remember that Objective-C is an extension of C). It confuses most people I know (like me) because it is surprising and you have to remember it.
As to a workaround: I would use uncleo's.
UncleO's answer is probably more robust, but if you want to do it on a single line, and you're certain the negative value will not be more negative than a single iteration of the mod (for example if you're only ever subtracting at most the mod value at any time) you can simplify it to a single expression:
int result = (n + 3) % 3;
Since you're doing the mod anyway, adding 3 to the initial value has no effect unless n is negative (but not less than -3) in which case it causes result to be the expected positive modulus.
There are two choices for the remainder, and the sign depends on the language. ANSI C chooses the sign of the dividend. I would suspect this is why you see Objective-C doing so also. See the wikipedia entry as well.
Not only java script, almost all the languages shows the wrong answer'
what coneybeare said is correct, when we have mode'd we have to get remainder
Remainder is nothing but which remains after division and it should be a positive integer....
If you check the number line you can understand that
I also face the same issue in VB and and it made me to forcefully add extra check like
if the result is a negative we have to add the divisor to the result
Instead of a%b
Use: a-b*floor((float)a/(float)b)
You're expecting remainder and are using modulo. In math they are the same thing, in C they are different. GNU-C has Rem() and Mod(), objective-c only has mod() so you will have to use the code above to simulate rem function (which is the same as mod in the math world, but not in the programming world [for most languages at least])
Also note you could define an easy to use macro for this.
#define rem(a,b) ((int)(a-b*floor((float)a/(float)b)))
Then you could just use rem(-1,3) in your code and it should work fine.