magma computer algebra system local and global variables - global-variables

function Max(x)
max := 0; L := [];
for i := 1 to x do
P2<x,y,z> := ProjectiveSpace(Rationals(),2);
C_i := Curve(P2, x^3+y^3-i*z^3);
E_i, C_itoE_i := EllipticCurve(C_i);
gen := Generators(E_i);
if max eq #gen then
max := #gen;
end if;
end for;
return max;
end function;
When I run this (Max(100)) it tells me that max = 0. However I know there are #gen = 1 and 2 at different places and therefore #gen > 0. I have having difficulty localizing max. It thinks of max outside the if and for statements as different than the max inside the for and if statements and thus is not updating max. I'm not sure how in magma CAS syntax I can correct for this. Can somebody help me understand Magma syntax with respect to this aspect?
I tried putting local max; inside the loop and if statements but gave me syntax error.

I don't know magma, but if it's anything like other procedural computer languages then it looks like you have a simple bug in your code. the lines:
if max eq #gen then
max := #gen;
end if;
should be changed to
if #gen > max then
max := #gen;
end if;
using whatever the the correct syntax is for the greater-than operator.

Related

How to count number of occurrences of a character in an array in Pascal

I have to script a pascal code that rations into calculation the frequency of a character's appearance in the code and displays it through the output mode
Input P2 changes:
Second Attempt at the coding phase
I tried revisioning the code.I added the output variable writeln('input array of characters'); & writeln('Number of Occurrences',k);, which should help me output how many times did the S character appear overall in the code, plus utilised the for & if commands to have the final values showcased based on the conditions, if the frequency is 1 then count in S, still getting errors, take a look at the Input P2 & Output P2
Input P1
function Count(t, s: String): Integer;
var
Offset, P: Integer;
begin
Result := 0;
Offset := 1;
P := PosEx(t, s, Offset);
while P > 0 do
begin
Inc(Result);
P := PosEx(t, s, P + 1);
end;
end;
Output P2
Target OS: Linux for x86-64
Compiling main.pas
main.pas(5,3) Error: Identifier not found "Result"
main.pas(7,8) Error: Identifier not found "PosEx"
main.pas(8,3) Error: Identifier not found "unsigned"
main.pas(8,12) Fatal: Syntax error, ";" expected but "identifier N" found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
-------------------------------------------------------------------
Input P2
program p1
var S:string
i:integer
begin
writeln('input array of characters');
k:=O;
for i:=1 to length (S) do
if (S[i])='m') and (S[i+1]='a') then k:=k+1;
writeln('Number of Occurrences',k);
Readln;
end.
Output P2
Compiling main.pas
main.pas(2,1) Fatal: Syntax error, ";" expected but "VAR" found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
The errors you see in the first block:
Identifier not found "Result"
Standard Pascal doesn't recognize the pseudovariable Result. In some Pascal implementations (like e.g. Delphi) it can be used to assign a value to the function result. The Pascal you are using needs to have the result of a function assigned to the name of the function. For example:
function Whatever(): integer;
begin
Whatever := 234;
end;
Identifier not found "PosEx"
Not all Pascal implementations include the PosEx() function. You need to use Pos() instead. But, the standard implementation of Pos() doesn't include the "search start position" that PosEx has. Therefore you need to ditch Pos() and do as you do in "Input P2", that is traverse the text character per character and count the occurances as you go.
Identifier not found "unsigned"
Seems you have removed that unknown identifier.
The error you see in the second block:
In Output P2 the error message should be clear. You are missing a semicolon where one is needed. Actually you are missing three of them.
You are also missing the line that reads user input: ReadLn(S);.
Finally, to calculate both upper and lower case characters you can use an extra string variable, say SU: string to which you assign SU := UpperCase(S) after reading user input, and then use that string to count the occurances.
I think this is more like what you want to do:
function Count(t, s: String): Integer;
var
Offset,Res, P: Integer;
begin
Res := 0
Offset := 1;
repeat
P := Pos(t, s, Offset);
if p>0 then
Inc(Res);
Offset := P+1
untl P = 0;
Count := Res;
end;
Now, if you don't have Pos, you can implement it:
Function Pos(const t,s:string; const Start:integer):Integer;
Var
LS, LT, {Length}
IxS, IxT, {Index)
R: Integer; {Result}
begin
R := 0;
{use only one of the two following lines of code}
{if your compiler has length}
LS := length(S); LT := Length(T);
{If it does not}
LS := Ord(s[0]); LT := Ord(T[0]);
if (LS <= LT) {if target is larger than search string, it's not there}
and (Start<=LT) and {same if starting position beyond size of S}
(Start+LT <-LS) then {same if search would go beyond size of S}
begin {Otherwise, start the search}
ixT := 1;
ixS := Start;
repeat
Inc(R); {or R:= R+1; if INC not available }
If (S[ixS] <> T[ixT]) then
R := 0 {they don't match, we're done}
else
begin {Move to next char}
Inc(ixS);
Inc(ixT);
end;
until (R=0) or (ixT>LT); {if search failed or end of target, done}
Pos := R;
end;

RSA procedure cryptology

Hi i was wondering if anyone can help me with the following procedure using maple
The protocol of the rsa decryption/encryption method is below and the question i am trying to attempt after that with my attempt below it, i will appreciate any help. Thanks
my current attempt is the following
rsa := proc (key::rsakey, msg::(list(rsascii)))
local ct, pe, pm, i;
pm := 26271227347;
pe := key[2];
ct := [];
for i to nops(msg) do ct := [op(ct), `mod`(message[i]^pe, pm)]
end do;
RETURN(ct)
end proc;
this was from using the maple website
You've been given n and e, and you'll need to find the corresponding d before you can decode. I don't understand why you were trying to use e to decode.
Your procedure contains at least one type, using message[i] instead of msg[i]. See also comments in the code below.
After finding d I get that the encoded integer 11393739244 decodes to the integer 87, which corresponds to the ASCII character "W" (not "wha" or "Wha" as you suggested).
I don't understand what you intend on doing about block size, and so I've had to guess. Below I show encoding/decoding done either A) a character at a time, or B) using three characters at once. I trust you realize that encoding one-character-at-a-time isn't a great idea. Also, in a duplicate post in another forum you wrote that you don't care about security against attack. (You also wrote there that this isn't homework, but here it looks like it more, IMO.)
If you had trouble writing and using your rsa procedure then you may find the various splitting/concetenating/padding operations tough also.
You wrote in a comment that when you tried to use your initial attempt at procedure rsa then, "it doesn't give anything back". If it returned as an unevaluated call then perhaps your attempt at creating the proc and assigning it didn't actually work. If you have trouble using Maple's default 2D Input mode in a Document then consider switching your preferences to 1D Maple Notation input in a Worksheet. Those are two Preferences for Maple's Standard Java GUI.
NB. I use Maple's numtheory[lambda] command to find "the smallest integer i such that for all g coprime to n, g^i is congruent to 1 modulo n". In recent Maple versions this is also avaliable as the command NumberThoery:-CarmichaelLambda. See also here.
restart;
# The procedure `rsa` below can be used to both encode or
# decode an integer.
#
# Conversion from/to ASCII is done separately, before/after.
rsa := proc(key::list(posint), msg::list(posint))
local ct, pe, pm, i;
pm := key[1];
pe := key[2];
## The original used `message` instead of `msg`, which was
## a careless typo. But iterated list concatenation like this
## is inefficient. Better to just use `seq`, as below.
## Also, use inert `&^` instead of `^` in the call to `mod`
## since the latter inefficiently computes the power
## explicitly (before taking the modulus).
#ct := [];
# for i to nops(msg) do ct := [op(ct), `mod`(msg[i] &^ pe, pm)]
#end do;
ct := map(u->`mod`(u &^ pe, pm), msg);
return ct;
end proc:
# You supplied (n,e) and you'll need to find d in order to decode.
n:=26271227347;
n := 26271227347
L := numtheory[lambda](n);
L := 13135445468
e:=11546465;
e := 11546465
evalb( e < L ); # a requirement
true
evalb( gcd(e, L) = 1); # a requirement
true
d := 1/e mod L;
d := 7567915453
# Now decode the number you supplied.
res := rsa([n,d],[11393739244]);
res := [87]
with(StringTools):
# So what ASCII character is that?
convert(res,bytes);
"W"
s := "Wha":
sb := map(convert,convert(s,bytes),string);
sb := ["87", "104", "97"]
sbn := map(parse,sb);
sbn := [87, 104, 97]
encoded := rsa([n,e],sbn);
encoded := [11393739244, 9911682959, 21087186892]
decoded := rsa([n,d],encoded);
decoded := [87, 104, 97]
pad := proc(str::string)
local r;
r := irem(length(str),3);
cat(seq("0",i=1..`if`(r=0,0,3-r)), str);
end proc:
map(pad, map(convert,decoded,string));
["087", "104", "097"]
cat(op(map(u->convert(map(parse,[LengthSplit(convert(u,string),3)]),
bytes), %)));
"Wha"
newsb := [cat(op(map(SubstituteAll,map(PadLeft,sb,3)," ","0")))];
newsb := ["087104097"]
newsbn := map(parse,newsb);
newsbn := [87104097]
encoded := rsa([n,e],newsbn);
encoded := [15987098394]
decoded := rsa([n,d],%);
decoded := [87104097]
map(pad, map(convert,decoded,string));
["087104097"]
cat(op(map(u->convert(map(parse,[LengthSplit(convert(u,string),3)]),
bytes), %)));
"Wha"

recursion using for do loop (pascal)

I'm trying to use the concept of recursion but using for do loop. However my program cannot do it. For example if I want the output for 4! the answer should be 24 but my output is 12. Can somebody please help me?
program pastYear;
var
n,i:integer;
function calculateFactorial ( A:integer):real;
begin
if A=0 then
calculateFactorial := 1.0
else
for i:= A downto 1 do
begin
j:= A-1;
calculateFactorial:= A*j;
end;
end;
begin
writeln( ' Please enter a number ');
readln ( n);
writeln ( calculateFactorial(n):2:2);
readln;
end.
There are several problems in your code.
First of all it doesn't compile because you are accessing the undefined variable j.
Calculating the factorial using a loop is the iterative way of doing it. You are looking for the recursive way.
What is a recursion? A recursive function calls itself. So in your case calculateFactorial needs a call to itself.
How is the factorial function declared?
In words:
The factorial of n is declared as
1 when n equals 0
the factorial of n-1 multiplied with n when n is greater than 0
So you see the definition of the factorial function is already recursive since it's referring to itself when n is greater than 0.
This can be adopted to Pascal code:
function Factorial(n: integer): integer;
begin
if n = 0 then
Result := 1
else if n > 0 then
Result := Factorial(n - 1) * n;
end;
No we can do a few optimizations:
The factorial function doesn't work with negative numbers. So we change the datatype from integer (which can represent negative numbers) to longword (which can represent only positive numbers).
The largest value that a longword can store is 4294967295 which is twice as big as a longint can store.
Now as we don't need to care about negative numbers we can reduce one if statement.
The result looks like this:
function Factorial(n: longword): longword;
begin
if n = 0 then
Result := 1
else
Result := Factorial(n - 1) * n;
end;

expression syntax for data.table := in R

I am having some trouble getting an eval within data.table in R to work with an expression. Here is some code:
dtb = data.table(a=1:100, b=100:1, id=1:10)
dtb[,`:=`(c=a+b, d=a/b),by=id] #this works fine
expr = expression({`:=`(c=a+b, d=a/b)}) #try to couch everything in an expression
dtb[,eval(expr),by=id] #this does not work
Error in `:=`(c = a + b, d = a/b) :
unused argument(s) (c = a + b, d = a/b)
expr = expression(`:=`(c=a+b, d=a/b)) #this works fine
dtb[,eval(expr),by=id]
Why does including {} break this?
See the definition of :=:
function (LHS, RHS)
stop(":= is defined for use in j only, and (currently) only once; i.e., DT[i,col:=1L] and DT[,newcol:=sum(colB),by=colA] are ok, but not DT[i,col]:=1L, not DT[i]$col:=1L and not DT[,{newcol1:=1L;newcol2:=2L}]. Please see help(\":=\"). Check is.data.table(DT) is TRUE.")
The assignment of a column doesn't happen within a call of :=--the function itself doesn't do anything besides produce an error. The assignment happens when [.data.table detectsj is an expression of the form `:=`(...) and then sets everything up for a call to the C code. When you enclose expr in brackets, you're making the first part of the expression { instead of :=, which passes by the above detection and eventually results in an evaluation of := with arguments c and d.
I guess that leads to the question, why do you need to enclose it in { }?
Issue #376 to trap the { around := has now been implemented in v1.8.11. From NEWS:
o FR #2496 is now implemented to trap and remove the { around := in j to obtain desired result. Now, DT[,{`:=`(...)}] and DT[, {`:=`(...)}, by=(...)] both work as intended but with a warning. Thanks to Alex for reporting on SO: expression syntax for data.table := in R

Maple: Why I can not plot my function which is definrd by proc?

So I created a proc that returns a value. (sqrt analog that is correct for numbers from (2.1) and up). I can evaluate it for any given number but I cannot plot it. Why and how to fix it?
code (converted to 1-d math input):
>
restart:
with(plottools):
val := 248;
sqr := proc (sqrtFrom, iterations) answer := 0; ampl := 0; number := sqrtFrom; for k to iterations do answer := 10*answer; number := sqrtFrom*10^ampl; for i from 0 while i < number do answer := answer+1; i := answer^2 end do; answer := answer-1; difr := -1; while difr < 0 do ampl := ampl+1; difr := sqrtFrom*10^ampl-100*answer^2 end do end do; return evalf(answer/10^(iterations-1)) end proc;
>
evalf(sqrt(val));
sqr(val, 10);
plot(sqr(x, 10), x = 3 .. 5);
>
You need eval quotes. Try
plot('sqr'(x,10), x = 3..5 );
The error you get is because sqr is being called prematurely with x as an argument, and it can't do that.
Alternatively, you can modify sqr itself to return unevaluated if it gets non-numeric arguments (which is how sqrt works).

Resources