Trial Divison Algorithm in Maple - encryption

I have the following code for Trial Divison Algorithm in Maple:
TrialDivision := proc( n :: integer )
if n <= 1 then
false
elif n = 2 then
true
elif type( n, 'even' ) then
false
else
for local i from 3 by 2 while i * i <= n do
if irem( n,i) = 0 then
return false
end if
end do;
true
end if
end proc:
which I got from http://rosettacode.org/wiki/Primality_by_trial_division#MATLAB. But when I try to run it, it is giving me the following error: Error, unexpected local declaration in procedure body.
Does anyone know what I am doing wrong?

Allowing local declarations throughout the procedure body is a somewhat recent addition to the Maple language.
You could change it to this, say.
TrialDivision := proc( n :: integer )
local i;
if n <= 1 then
false
elif n = 2 then
true
elif type( n, 'even' ) then
false
else
for i from 3 by 2 while i * i <= n do
if irem( n,i) = 0 then
return false
end if
end do;
true
end if
end proc:

Related

Function that will return the biggest number of consecutive 0's

For a homework problem, in python we are asked to define in a recursive way a function that will return the biggest number of consecutive 0's in binary for any the number n. We need to use "&" and ">>".
For example, the function should return 2 for n = 44 because its binary representation is 101100.
I do not know where to go from here. Any help would be appreciated!
def max_consecutive_zero_iterative(n):
res = 0
streak = 0
while n > 0:
if n & 1:
streak = 0
else:
streak += 1
n = n >> 1
res = max(res, streak)
return res
def max_consecutive_zero_recursive(n):
if n == 0: # end of recursion
return 0
value = max_consecutive_zero_recursive(n >> 1) # call to recursive
current_streak = value & 0xff # current streak is stored in the lowest 8 bits
longest_streak = value >> 8 # longest streak is stored in the upper bits
if n & 1: # if we have a bit set
return max(longest_streak, current_streak) << 8 # we just return the max value between current_streak and longest_streak, stored in upper bits
# else if the bit is not set
current_streak += 1 # we increase our current streak by 1
# and return the max between the longest_streak and current_streak in the upper bits...
return max(longest_streak, current_streak) << 8 | current_streak
# ... but this time we keep information (we don't reset) about the current_streak stored in the lowest 8 bits.
def main():
print(max_consecutive_zero_recursive(0b1000101111000110000000100110) >> 8)
if __name__ == "__main__":
main()

Skipping calculation of somes primes when asking lot of primes

I just started to learn some ada code and would create my very own primes calculator.
To procress, I use one of most known method, which is :
"each primes is a result of 6 * x -+ 1 "
So this is my code :
with Ada.Text_IO, Ada.Integer_Text_IO ;
use Ada.Text_IO, Ada.Integer_Text_IO ;
procedure main is
count_prime : Integer := 0 ;
counter : Integer := 1 ;
wanted : Integer ;
iteration : Integer := 0 ;
testing : Integer := 0 ;
is_prime : Boolean ;
answer : Character ;
begin
loop
Put("Prime calculator") ;
New_line(2) ;
Put("Put 'p' to process") ;
New_Line(1);
Put("Put 'q' to quit") ;
New_Line(2) ;
Put(">> ") ;
Get(answer) ;
if answer = 'p' then
Put("Enter wanted primes :");
Get(wanted) ;
Skip_line ;
if wanted > 0 then
Put("2");
New_Line(1);
if wanted > 1 then
Put("3");
New_Line(1);
end if ;
if wanted > 2 then
count_prime := 2;
loop
if counter = 1 then
counter := 0 ;
iteration := iteration + 1 ;
testing := ( 6 * iteration ) - 1 ;
else
counter := 1 ;
testing := ( 6 * iteration ) + 1 ;
end if ;
is_prime := True ;
for i in 2..(testing-1) loop
if (testing rem i = 0) then
is_prime := False ;
end if ;
end loop;
if is_prime = True then
Put(testing);
New_Line(1);
count_prime := count_prime + 1 ;
end if ;
exit when count_prime = wanted;
end loop ;
end if;
Put("Ended") ;
else
Put("It's can't be a negative number");
end if ;
end if ;
New_Line(3);
exit when answer = 'q' ;
end loop ;
end main ;
I really know this is a basic, I mean ouh, extremely basic program. But I would just solve the problem I've asked :
with 'p' and 2 :
2
3
with 'p' and '7'
2
3
5
7
11
13
17
with 'p' and 1200
2
3
19
23
29
31
37
41
....
Where are gone all primes between 3 and 19 ?
You keep running the calculation in a cycle, but do not reset it's initial state. The loop that performs the calculation continues using values of iteration, counter and a few other variables from the previous run.
Either decompose the loop into a separate procedure, or at least surround it with declare block, e.g.:
declare
count_prime : Integer := 2;
counter : Integer := 1;
iteration : Integer := 0;
testing : Integer := 0;
is_prime : Boolean;
begin
loop
…
end loop;
end;
However, I'd strongly recommend decomposing into a separate procedure.
if wanted > 2 then
count_prime := 2;
-- you probably want to reset iteration here...
iteration := 0;
loop
if counter = 1 then

Solving 4X4 sudoku in maple

So I am trying to use recursion and backtracking to solve a 4x4 sudoku.
When I call SolveSmallSudoku(L);
"Solving now..."
it gives me this "Error, (in SolveSmallSudoku) Matrix index out of range"
But I cannot spot any bug that is related to my matrix, L, indices. It seems like that my program doesn't do my backtracking part properly. I think my findPossibleEntries procedure works fine. It does find all the possible values for that certain cell. Anyone got any hint?
> L := Matrix(4,4,[ [0,4,0,0],[2,0,0,3],[4,0,0,1],[0,0,3,0] ]);
> isFull := proc(L)
local x, y;
for x from 1 to 4 do
for y from 1 to 4 do
if L[x,y]=0 then
return false;
end if;
end do;
end do;
return true;
end proc;
>findPossibleEntries := proc(L, i, j)
local x, y, possible:=[0,0,0,0];
local r:=1, c:=1;
#Checking possible entries in ith row
for y from 1 to 4 do
if not L[i,y] = 0 then
possible[L[i,y]] := 1;
end if;
end do;
#Checking possible entries in jth col
for x from 1 to 4 do
if not L[x,j] = 0 then
possible[L[x,j]] := 1;
end if;
end do;
#Checking possible entries block by block
if i >= 1 and i <= 2 then
r := 1;
elif i >= 3 and i <= 4 then
r := 3;
end if;
if j >= 1 and j <= 2 then
c := 1;
elif j >= 3 and j <= 4 then
c := 3;
end if;
#Using for-loop to find possible entries in the block
for x in range(r, r+1) do
for y in range(c, c+1) do
if not L[x,y] = 0 then
possible[L[x,y]] := 1;
end if;
end do;
end do;
#Now the list, possible, only holds the possible entries
for x from 1 to 4 do
if possible[x] = 0 then
possible[x] := x;
else
possible[x] := 0;
end if;
end do;
return possible;
end proc;
>SolveSmallSudoku := proc(L)
local x, y, i:=0, j:=0, possibleVal:=[0,0,0,0];
if isFull(L) then
print("Solved!");
print(L);
return;
else
print("Solving now...");
for x from 1 to 4 do
for y from 1 to 4 do
if L[x,y] = 0 then
i:=x;
j:=y;
break;
end if
end do;
#Breaks the outer loop as well
if L[x,y] = 0 then
break;
end if
end do;
#Finds all the possibilities for i,j
possibleVal := findPossibleEntries(L,i,j);
#Traverses the list, possibleVal to find the correct entries and finishes the sudoku recursively
for x from 1 to 4 do
if not possibleVal[x] = 0 then
L[i,j]:= possibleVal[x];
SolveSmallSudoku(L);
end if;
end do;
#Backtracking
L[i,j]:= 0;
end if;
end proc;
Get rid of,
#Breaks the outer loop as well
if L[x,y] = 0 then
break;
end if
As you had it originally that outer check was trying to access L[1,5] for your given example L.
Instead, replace the break in the inner loop with,
x:=4; break;
That will cause the outer loop to also complete at the next iteration (which happens to occur right after the inner loop ends or breaks. So you'll get the full break you wanted.
The code then seems to work as you intended, and the solution gets printed for your input example.

how to print variables in gmlp

I have a linear programming model, for the problem of minimum path. This is the model:
/* Min path problem
file: minPath.mod */
set V;
set E within V cross V;
param cost{E};
param S symbolic;
param T symbolic;
var flow{E} integer, >= 0;
minimize min_path: sum{(a,b) in E} cost[a,b] * flow[a,b];
s.t. conservazione{v in V: v != S and v != T}:
sum{(a,b) in E: a == v} flow[a,b] ==
sum{(a,b) in E: b == v} flow[a,b];
s.t. sorgente: sum{(a,b) in E: a == S} flow[a,b] == 1;
s.t. destinazione: sum{(a,b) in E: b == T} flow[a,b] == 1;
display {(a,b) in E} flow[a,b];
data;
set V := A B C D E;
set E := (A,B) (A,C) (B,D) (B,E) (C,D) (D,E);
param S := A;
param T := D;
param cost := [A,B] 2 [A,C] 1 [B,D] 3 [B,E] 1 [C,D] 1 [D,E] 1;
end;
The objective value is 3 for my example, and the minimum path is:
A -> C -> D -> E
For this reason, the vector flow has to be 1 on the edges, that i written here above. By the way, when i display the vector flow with the statement:
display {(a,b) in E} flow[a,b];
the vector is 0 in all the position.
flow[A,B].val = 0
flow[A,C].val = 0
flow[B,D].val = 0
flow[B,E].val = 0
flow[C,D].val = 0
flow[D,E].val = 0
I tried to change the syntax, but i couldn't force glpsol to print the real value.
Am I missing something?
you have to put the statement:
solve;
before the display statement!

SML and functional coding style

I'm start to learn Standard ML with Programming languages course.
In the first homework, I try to write a function is_older that takes two dates and evaluates to true or false. It evaluates to true if the first argument is a date that comes before the second argument (If the two dates are the same, the result is false.).
So I write the following code:
fun is_older(first: int * int * int, second: int * int * int) =
if(#1 first = #1 second andalso #2 first = #2 second andalso #3 first = #3 second) then false
else if (#1 first < #1 second) then true
else if (#1 first = #1 second andalso #2 first < #2 second) then true
else if (#1 first = #1 second andalso #2 first = #2 second andalso #3 first < #3 second) then true
else false
The code is works fine, but it looks ugly.
How can I rewrite this code in functional style?
Two suggestions:
Use pattern matching to decompose tuples.
Use boolean operators (andalso, orelse, etc.) when if/else constructs return boolean.
A more readable version:
(* Compare two dates in the form of (year, month, day) *)
fun is_older((y1, m1, d1), (y2, m2, d2)) =
y1 < y2 orelse (y1 = y2 andalso m1 < m2)
orelse (y1 = y2 andalso m1 = m2 andalso d1 < d2)
In general when you have something on the form
if b then
true
else
false
you should exchange it with just b, as it is seen trivially to be the same.
The solution provided by pad would probably also have been my solution, as it is nice and short.
However when you end up having those nasty/nested if-then-else's, and you don't return something simple (e.g., true/false or a number), then you should consider using a case. Your function is not a prime candidate to use, however I hope the below still shows the idea (that you easily can make structure of those nested if's)
fun is_older((y1, m1, d1), (y2, m2, d2)) =
case (Int.compare(y1,y2), Int.compare(m1,m2), Int.compare(d1, d2)) of
(LESS , _ , _ ) => true
| (EQUAL, LESS , _ ) => true
| (EQUAL, EQUAL, LESS) => true
| _ => false
fun is_older((yr1 : int , mo1 : int , dt1 : int), (yr2 : int , mo2 : int , dt2 : int )) =
yr1 < yr2 orelse (yr1 = yr2 andalso mo1 < mo2)
orelse (yr1 = yr2 andalso mo1 = mo2 andalso dt1 < dt2)

Resources