CA I - Exercise sheet 08

Exercise 1: ( Modular power)

Clear[powermod];
powermod[a_,0,p_]:=1;
powermod[a_,n_,p_]:=Module[{binary},
binary=IntegerDigits[n,2];
m=Length[binary];
sol=1;
For[i=1,i≤ m,i++,
sol=Mod[sol^2,p]; (* immer Quadrieren Q *)
If[binary[[i]]==1,sol=Mod[sol a,p]]; (* nur bei 1 zusätzlich Multiplizieren M *)
];
sol
]

powermod[123456789101112,123456789101112,654321]

PowerMod[123456789101112,123456789101112,654321]

powermod[23,65,45830987]

PowerMod[23,65,45830987]

Gut sample solution proposed by some students!!!!!!!!!!!

The functions EANCheck, ISBNCheck return a value indicating whether the corresponding number is valid. If one is not correct these functions throw a message that describes the reason of this.

Clear[EANCheck,ISBNCheck];

EANCheck::IncorrectNumberOfDigits="The input integer must have 13 digits.";
EANCheck::InvalidCheckDigit="The check digit should be `1`.";
EANCheck::InvalidCharacter="The input contains an invalid character '`1`'.";

EANCheck[n_]:=Module[{l,s,digit,ch,check,r=False,fail},
If[StringLength[n]==13,
l=Characters[n];s=0;fail=False;
Do[ch=l[[i]];
If[DigitQ[ch],
digit=First[ToCharacterCode[ch]-48];
If[BitAnd[i,1]==1,s+=digit,s+=3 digit],
Message[EANCheck::InvalidCharacter,ch];fail=True;Break[]],
{i,1,12}];
If[fail,Return[]];
ch=Last[l];
If[DigitQ[ch],
digit=First[ToCharacterCode[ch]-48];
check=Mod[-s,10];
If[check==digit,r=True,
Message[EANCheck::InvalidCheckDigit,check];r=False],
Message[EANCheck::InvalidCharacter,ch];Return[]],
Message[EANCheck::IncorrectNumberOfDigits], Return[]];
r]/;StringQ[n];

ISBNCheck::IncorrectNumberOfDigits="The input integer must have 10 digits.";
ISBNCheck::InvalidCheckDigit="The check digit should be `1`.";
ISBNCheck::InvalidCharacter="The input contains an invalid character '`1`'.";

ISBNCheck[n_]:=Module[{l,s,digit,ch,check,r=False,fail},
If[StringLength[n]==10,
fail=False;l=Characters[n];s=0;
Do[ch=l[[i]];
If[DigitQ[ch] ,
digit=First[ToCharacterCode[ch]-48];
s+=(11-i) digit,
Message[ISBNCheck::InvalidCharacter,ch];fail=True;Break[]],
{i,1,9}];
If[fail,Return[]];
ch=ToUpperCase[Last[l]];
If[DigitQ[ch] || ch=="X",
If[DigitQ[ch],digit=First[ToCharacterCode[ch]-48]];
If[ch=="X",digit=10];
digit=Mod[digit,11];
check=Mod[-s,11];
If[check==digit,r=True,
If[check==10,check="X"];
Message[ISBNCheck::InvalidCheckDigit,check];r=False],
Message[ISBNCheck::InvalidCharacter,ch];Return[]],
Message[ISBNCheck::IncorrectNumberOfDigits], Return[]];
r]/;StringQ[n];

EANCheck["9783540298946"]&&EANCheck["2231414447770"]&&EANCheck["0000536973687"]

EANCheck["0001153697469"]

ISBNCheck["3540298940"]&&ISBNCheck["003115364X"]&&ISBNCheck["2341709559"]

ISBNCheck["2341709554"]