boolean logic Are both boolean logic equal - boolean-logic

A && B || C && D
(A && B) || (C && D)
Are both boolean logic equal in C++? I am confused.

Whether or not they're equal depends entirely on how you define your operator precedence. If && takes precedence over ||, then yes. Otherwise, no.

In the most programming languages you'll find that operator && is of higher priority than ||.
So for example in Java, C#, C, C++, Python, Ruby, etc.
A && B || C && D
is equivalent to
(A && B) || (C && D)
You can even copy-paste the code:
#include <iostream>
using namespace std;
int main() {
bool A = false;
bool B = false;
bool C = true;
bool D = true;
for(int i = 0; i < 2; ++i) {
A = (i == 0);
for(int j = 0; j < 2; ++j) {
B = (j == 0);
for(int k = 0; k < 2; ++k) {
C = (k == 0);
for(int l = 0; l < 2; ++l) {
D = (l == 0);
cout << A << " " << B << " " << C << " " << D << " -> ";
cout << ((A && B || C && D) == ((A && B) || (C && D))) << endl;
}
}
}
}
return 0;
}
to Ideone to find out for yourself. In C++ for example the output is:
1 1 1 1 -> 1
1 1 1 0 -> 1
1 1 0 1 -> 1
1 1 0 0 -> 1
1 0 1 1 -> 1
1 0 1 0 -> 1
1 0 0 1 -> 1
1 0 0 0 -> 1
0 1 1 1 -> 1
0 1 1 0 -> 1
0 1 0 1 -> 1
0 1 0 0 -> 1
0 0 1 1 -> 1
0 0 1 0 -> 1
0 0 0 1 -> 1
0 0 0 0 -> 1
So the ((A && B || C && D) == ((A && B) || (C && D))) is a tautology.

While the final answer goes to the specifics of the C++ language you're asking about, here's some food for thought on why (and possibly how) to remember:
Conjunction (AND, &&) is often associated with multiplication, while disjunction (OR, ||) is often associated with addition (and we generally know the precedence of multiplication over addition).
Here's a quote from http://www.ocf.berkeley.edu/~fricke/projects/quinto/dnf.html:
... As a practical matter, we usually associate conjunction with
multiplication and disjunction with addition. Indeed, if we identify
true with 1 and false with 0, then {0,1} coupled with the usual
definitions of addition and multiplication over the Galois field of
size 2 (eg, arithmetic modulo 2), then addition (+) and disjunction
(or) really are the same, as are multiplication and conjunction (and).
...
Speaking in rather general terms, the computer languages tend to honor the precedence of multiplicative operators over additive operators.
(Further, these associations, e.g. between operators in logic and in algebra reoccur in other areas, such as type systems. For an interesting exposition of that, see http://blog.lab49.com/archives/3011 on the notion of Algebraic Type Systems.)

Related

Dafny GCD lemma Proof

I'd like to use dafny to prove the following lemma about GCD: For all k natural numbers, if k|a and k|b, then k|gcd(a,b). I have the following code so far:
// Euclid's algorithm for computing the greatest common divisor
function gcd(a: nat, b: nat): nat
requires a > 0 && b > 0
{
if a == b then a else
if b > a then gcd(a, b - a) else
gcd(a - b, b)
}
predicate divides(a: nat, b:nat)
requires a > 0
{
exists k: nat :: b == k * a
}
lemma dividesLemma(a: nat, b: nat)
//k|a && k|b ==> k|gcd(a,b)
requires a > 0 && b > 0
ensures gcd(a,b) > 0
ensures forall k: nat :: divides(a,k) && divides(b,k) ==> divides(gcd(a,b),k)
{
if(a == b) {
assert a * 1 == gcd(a,b);
assert b * 1 == gcd(a,b);
} else if b > a {
if(divides(a, b)) {
assert divides(a,a);
assert divides(a,b);
assert divides(a, gcd(a,b));
} else {
dividesLemma(a, b - a);
}
} else {
if(divides(b, a)) {
assert divides(b,b);
assert divides(b,a);
assert divides(b, gcd(a,b));
} else {
dividesLemma(a, a - b);
}
}
}
I know how to do the proof for this by hand. I would consider the prime factorization of a and b and say that gcd(a,b) was the combined prime factorization such that we take the minimal number of primes from each prime factorization. For instance if a = 9 and b = 15, the prime factorization of 9 = 3x3 and the prime factorization of 15 = 3x5, so the gcd(9,5) = 3 since that's the minimal combination of their prime factoizations. Using this fact it should be clear that if k|b and k|a, k must contain those minimal primes. How can I express this using dafny? Currently, I'm considering the base case if a=b and if a|b or b|a, but not sure how to incorporate the fact that it's possible for a and b to not share common primes in their prime factorizations.
Any help would be much appreciated for this!
There is problem in how divides is being called. I think
in ensures clauses you meant divides(k, a) instead of divides(a, k)
similarly for divides(b, k) and divides(gcd(a, b), k).
One way to go about this after recursive call to dividesLemma(a, b - a) is
to use postcondition of method. Here we know forall k such that k divides a and k divides b - a implies k divides gcd(a, b-a). Using this information we try to prove required postcondition (code or proof is straightforward to follow)
dividesLemma(a, b - a);
assert gcd(a, b) == gcd(a, b-a);
assert forall k : nat :: k > 0 && divides(k, a) && divides(k, b-a) ==> divides(k, gcd(a, b));
forall k : nat | k > 0 && divides(k, a) && divides(k, b) ensures divides(k, gcd(a, b)) {
var m :| a == m * k;
var n :| b == n * k;
assert (b - a) == (n - m) * k;
assume n >= m;
assert divides(k, a);
assert divides(k, b-a);
// Implied from last assert forall
assert divides(k, gcd(a, b));
}
Here I am assuming n >= m because divides requires n-m to be nat, which can proved separately.
Also second recursive call should be dividesLemma(a - b, b).
function gcd(a: nat, b: nat): nat
requires a > 0 && b > 0
{
if a == b
then a
else if a < b
then gcd(a, b-a)
else gcd(a-b, b)
}
predicate divides(a: nat, b: nat)
requires a > 0 && b > 0
{
exists k: nat :: b == k * a
}
lemma helper(a: nat, b: nat, k : nat)
requires a > 0 && b > 0 && k > 0
requires divides(k, a) && divides(k, b)
requires b >= a
ensures exists m, n :: a == m * k && b == n * k && m <= n;
{ }
lemma dividesLemma(a: nat, b: nat)
decreases a + b
requires a > 0 && b > 0
ensures gcd(a, b) > 0
ensures forall k: nat :: k > 0 && divides(k, a) && divides(k, b) ==> divides(k, gcd(a, b))
{
if (a == b){
}
else if (b > a){
dividesLemma(a, b - a);
assert gcd(a, b) == gcd(a, b-a);
assert forall k : nat :: k > 0 && divides(k, a) && divides(k, b-a) ==> divides(k, gcd(a, b));
forall k : nat | k > 0 && divides(k, a) && divides(k, b) ensures divides(k, gcd(a, b)) {
helper(a, b, k);
var m, n :| a == m * k && b == n * k && m <= n;
assert b - a == (n - m) * k;
assert divides(k, b-a);
}
}
else {
dividesLemma(a - b, b);
assert gcd(a, b) == gcd(a - b, b);
assert forall k : nat :: k > 0 && divides(k, a-b) && divides(k, b) ==> divides(k, gcd(a, b));
forall k : nat | k > 0 && divides(k, a) && divides(k, b) ensures divides(k, gcd(a, b)) {
helper(b, a, k);
var m, n :| b == m * k && a == n * k && m <= n;
assert a - b == (n - m) * k;
assert divides(k, a-b);
}
}
}

How to write the signum fuction in haskell (Type problem)

I want to write the signum function in Haskell but i can't figure out how to properly
write the type singature so that the function works.
signum1 :: Num a => a -> Int
signum1 x | x == 0 = 0
| x > 0 = 1
| x < 0 = -1
For every parameter of the Num class the result should either be 0, 1 or -1 from the type Int.
So signum1 0.9 should give 1 as result (not 1.0).
You are missing an Ord a constraint, such that we can compare the value with > 0, < 0, and since Ord a is a subclass of Eq a, we thus can also work with == 0:
signum1 :: (Num a, Ord a) => a -> Int
signum1 x | x == 0 = 0
| x > 0 = 1
| x < 0 = -1
The last guard is not necessary, we can use otherwise for that (which is an alias of True):
signum1 :: (Num a, Ord a) => a -> Int
signum1 x | x == 0 = 0
| x > 0 = 1
| otherwise = -1

Function to return a part of a list

I am new to Haskell and have an assignment. I have to write a
Int->Int->[u]->[u]
Function that is given input two Ints i and j and a list and returns the elements that are in possitions greater than i and smaller than j. What I have thought so far is:
fromTo :: Int->Int->[u]->[u]
fromTo i j (h:t)
|i == 1 && j == length(h:t)
= (h:t)
|i /= 1
fromTo (i-1) j t
|j /= length(h:t)
fromTo i j init(h:t)
However I get a syntax error for the second |. Also im unsure if my train of thought is correct here.
(init returns the list without its last element)
EDIT: Corrected
|i /= 1
fromTo (i-1) j (h:t)
to
|i /= 1
fromTo (i-1) j t
Fixed indentation, parenthesization, and missing =s. This reformation compiles, and works for ordinals and finite non-empty lists:
fromTo :: Int -> Int -> [u] -> [u]
fromTo i j (h : t)
| i == 1 && j == length (h : t) = h : t
| i /= 1 = fromTo (i - 1) j t
| j /= length (h : t) = fromTo i j (init (h : t))
I think you're looking for something like this pointfree, naturally indexing span:
take :: Int -> [a] -> [a]
take _ [] = []
take 0 _ = []
take n (x : xs) = x : take (n - 1) xs
drop :: Int -> [a] -> [a]
drop _ [] = []
drop 0 xs = xs
drop n (_ : xs) = drop (n - 1) xs
span :: Int -> Int -> [a] -> [a]
span i j = drop i . take (j + 1)
which
span 0 3 [0 .. 10] == [0,1,2,3]
Or, to fit the specification:
between :: Int -> Int -> [a] -> [a]
between i j = drop (i + 1) . take j
which
between 0 3 [0 .. 10] == [1,2]
You're missing = between the | guard clause and the body. The Haskell compiler thinks the whole thing is the guard, and gets confused when it runs into the next | guard because it expects a body first. This will compile (although it is still buggy):
fromTo :: Int -> Int -> [u] -> [u]
fromTo i j (h:t)
| i == 1 && j == length (h:t) =
(h:t)
| i /= 1 =
fromTo (i-1) j t
| j /= length (h:t) =
fromTo i j (init (h:t))
but I would say there are better ways of writing this function. For example, in principle a function like this should work on infinite lists, but your use of length makes that impossible.
Here is complete solution that use recursion:
fromTo :: Int -> Int -> [u] -> [u]
fromTo i j xs = go i j xs []
where go i j (x:xs) rs
| i < 0 || j < 0 = []
| i > length (x:xs) || j > length (x:xs) = []
| i /= 0 = go (i - 1) j t
| j /= 1 = goo i (j -1) (rs ++ [x])
| otherwise = rs
Notes:
go is standard Haskell idiom for recursive function that need extra parameters compared to main level function.
First clause make sure that negative indexes result in empty list. Second does the same for any index that exceed size of a list. Lists must be finite. Third "forgets" head of the array i times. Fourth will accumulate "next" (j - 1) heads into rs. Fifth clause will be triggered when all indexes are "spent" and rs contain result.
You could make it work on infinite lists. Drop second clause. Return rs if xs is empty before "exhausting" indexes. Then function will take "up to" (j-1) elements from i.

Binary division with decimals

I wrote this small program to divide two 8 bit numbers with decimals (4 bit before and after comma):
void main()
{
// All numbers are in the format xxxx,xxxx
unsigned char a = 0b00010000; // Dividend = 1,0
unsigned char b = 0b00100000; // Divisor = 2,0
unsigned char r = 0; // Result
// Align divisor to the left
while ((b & 0b10000000) == 0)
{
b = (b << 1) & 0b11111110;
}
// Calculate all 8 bits
for (unsigned char i = 0; i < 8; ++i)
{
if (a < b)
{
// Append 0 to the result
r = (r << 1) & 0b11111110;
}
else
{
// Append 1 to the result
r = (r << 1) | 1;
a = a - b;
}
b = b >> 1;
}
printBinary(r);
getchar();
}
But all my results are shift to the left one digit too much.
So my results are 2 times bigger than they should.
I am so dump, even if I try to calculate 1 / 2 per hand I am making the same mistake:
0001,0000 / 0010,0000 = 0001,0000
0001,0000 / 1000,0000
-1000,0000 -> 0
0001,0000 / 0100,0000
-0100,0000 -> 0
0001,0000 / 0010,0000
-0010,0000 -> 0
0001,0000 / 0001,0000
-0001,0000 -> 1
0000,0000 / 0000,1000
-0000,1000 -> 0
0000,0000 / 0000,0100
-0000,0100 -> 0
0000,0000 / 0000,0010
-0000,0010 -> 0
0000,0000 / 0000,0001
-0000,0001 -> 0
Whats my mistake?

Miller–Rabin SPOJ WA

I am trying to implement Miller-Rabin for the first time. My code is giving correct answer for all the testcases, i tried but still on SPOJ it is giving wrong answer.
Problem Statement: I am supposed to print "YES" if entered number is prime otherwise "NO"
Please help:
Problem Link: http://www.spoj.com/problems/PON/
CODE:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define LL long long
LL expo(LL a,LL b,LL c)
{
LL x=1,y=a;
if(b==0)
return 1;
while(b)
{
if(b%2==1)
x=(x*y)%c;
y=(y*y)%c;
b=b/2;
}
return x;
}
int main()
{
LL t,s,x,a,n,prime,temp;
scanf("%lld",&t);
srand(time(NULL));
while(t--)
{
scanf("%lld",&n);
if(n<2)
puts("NO");
else if(n==2)
puts("YES");
else if(n%2==0)
puts("NO");
else
{
s=n-1;
prime=1;
while(s%2==0)
s=s/2;
for(int i=0;i<20;i++)
{
a=rand()%(n-1)+1;
x=expo(a,s,n);
temp=s;
while((temp!=n-1)&&(x!=1)&&(x!=n-1))
{
x=(x*x)%n;
temp*=2;
}
if((x!=n-1)&&(temp%2==0))
{
prime=0;
break;
}
}
if(prime==0)
puts("NO");
else
puts("YES");
}
}
return 0;
}
Keep in mind that puts appends a newline character '\n' to the string that you're giving. You can try with printf instead.
I think your calculation of s and d is incorrect:
function isStrongPseudoprime(n, a)
d := n - 1; s := 0
while d % 2 == 0
d := d / 2; s := s + 1
t := powerMod(a, d, n)
if t == 1 return ProbablyPrime
while s > 0
if t == n - 1 return ProbablyPrime
t := (t * t) % n
s := s - 1
return Composite
I discuss the Miller-Rabin method in an essay at my blog.
You are getting wrong answer because of integer overflow as you are multiplying 2 long number which can't be holded in a single long long type.
Here is a solution in python to overcome the issue
import random
_mrpt_num_trials = 25 # number of bases to test
def is_probable_prime(n):
assert n >= 2
# special case 2
if n == 2:
return True
# ensure n is odd
if n % 2 == 0:
return False
# write n-1 as 2**s * d
# repeatedly try to divide n-1 by 2
s = 0
d = n - 1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
assert(2 ** s * d == n - 1)
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True
for _ in range(_mrpt_num_trials):
a = random.randrange(2, n)
if try_composite(a):
return False
return True
for i in range(int(input())):
a = int(input())
if is_probable_prime(a):
print("YES")
else:
print("NO")