Karim Belabas on Fri, 31 Jan 2025 02:08:29 +0100


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: program to verify ISBN numbers (10 digit or 13 digit)


Here's a further shortened version.

verify_isbn(N)=
{ my(M, n, z);
  M = Map([10, [[10,9,8,7,6,5,4,3,2,1]~, 11];
           13, [[1,3,1,3,1,3,1,3,1,3,1,3,1]~, 10]]);
  n = if (type(N)=="t_STR", apply(eval, select(c -> c != "-", Vec(N))),
          type(N)=="t_INT", digits(N));
  if (!mapisdefined(M, #n, &z) || (n * z[1]) % z[2], print("Invalid! ", N)
                                                   , print("Valid ISBN: ", N));
}

Cheers,

    K.B.
-- 
Pr. Karim Belabas, U. Bordeaux, Vice-président en charge du Numérique
Institut de Mathématiques de Bordeaux UMR 5251 - (+33) 05 40 00 29 77
http://www.math.u-bordeaux.fr/~kbelabas/

* Loïc Grenié [2025-01-30 23:15]:
>      Hi,
> 
> On Thu 30 Jan, 2025, at 21:43, American Citizen wrote:
> 
>> Hello All:
>>
>> I had to verify some ISBN numbers and didn't know that they actually
>> followed a well ordered scheme for being checked.
>>
>> For anyone who wants it, here's the GP-Pari program to verify the number
>> or string value (removing the dashes)
>>
>> {verify_isbn(N)=
>> my(m10,m13,m,n,sz,z);
>> m10=[10,9,8,7,6,5,4,3,2,1]~;
>> m13=[1,3,1,3,1,3,1,3,1,3,1,3,1]~;
>> if(type(N)=="t_STR",
>>   m=Vec(N);
>>   sz=matsize(m)[2];
>>   n=0;
>>   for(i=1,sz,if(m[i]!="-",n=concat(n,eval(m[i]));););
>>   sz=matsize(n)[2];
>>   n=vector(sz-1,i,n[i+1]);
>> );
>> if(type(N)=="t_INT", n=digits(N););
>> if(default(debug)>0,print("n=",n));
>> if(matsize(n)[2]==13,
>>   z=n*m13;
>>   if(z%10==0,print("Valid ISBN: ",N);,print("Invalid! ",N););
>>   return;
>> );
>> if(matsize(n)[2]==10,
>>   z=n*m10;
>>   if(z%11==0,print("Valid ISBN: ",N);,print("Invalid! ",N););
>>   return;
>> );
>> print("Invalid ISBN: ",N);
>> }
>>
> 
>      I have slightly streamlined it. It is possible to make it shorter,
>   I have not pushed in that direction.
> 
>          Cheers,
> 
>             Loïc
> 
> verify_isbn(N)=
> {
>     my(m10,m13,n,z);
> 
>     m10=[10,9,8,7,6,5,4,3,2,1]~;
>     m13=[1,3,1,3,1,3,1,3,1,3,1,3,1]~;
> 
>     if(type(N)=="t_STR",
>         n=apply(eval,select(c->c!="-",Vec(N)));
>     ,
>         type(N)=="t_INT",
>         n=digits(N);
>     );
>     if(default(debug)>0,print("n=",n));
>     if(#n==13,
>         z=n*m13;
>         if(z%10==0,print("Valid ISBN: ",N);,print("Invalid! ",N););
>     ,
>         #n==10,
>         z=n*m10;
>         if(z%11==0,print("Valid ISBN: ",N);,print("Invalid! ",N););
>     ,
>         print("Invalid ISBN: ",N);
>     );
> }