Upload
diego-gonzalez-vasquez
View
611
Download
0
Embed Size (px)
Citation preview
Si eso para quienes estan aproblemados aca van las soluciones de la rutina del digito verificador
del rut
NATURAL, EN PALABRAS:
ALGORITMO 1
1. Multiplicar cada dígito del RUT se por 2, 3, ..., 7, 2, 3, ... de atrás hacia adelante.
2. Sumar las multiplicaciones parciales.
3. Calcular el resto de la división por 11
4. El Dígito Verificador es 11 menos el resultado anterior. Si es 10, se cambia por 'k'.
EJEMPLO. RUT: 11.222.333
1. 1 1 2 2 2 3 3 3 <-- RUT
* 3 2 7 6 5 4 3 2 <-- 2, 3, 4, 5, 6, 7, 2, 3, ...
--------------------------------------
3 2 14 12 10 12 9 6
2. SUMA: 3 + 2 + 14 + 12 + 10 + 12 + 9 + 6 = 68
3. 68 : 11 = 6
- 66
----
2 <-- RESTO
4. 11 - 2 = 9 <-- DÍGITO VERIFICADOR
______________________________________________________
ALGORITMO 2, versión alternativa
1. Multiplicar cada dígito del RUT se por 9, 8, ..., 4, 9, 8, ... de atrás hacia adelante.
2. Sumar las multiplicaciones parciales.
3. Calcular el resto de la división por 11
4. El Dígito Verificador es el resultado anterior. Si es 10, se cambia por 'k'.
EJEMPLO. RUT: 11.222.333
1. 1 1 2 2 2 3 3 3 <-- RUT
* 8 9 4 5 6 7 8 9 <-- 9, 8, 7, 6, 5, 4, 9, 8, ...
--------------------------------------
8 9 8 10 12 21 24 27
2. SUMA: 8 + 9 + 8 + 10 + 12 + 21 + 24 + 27 = 119
3. 119 : 11 = 10
- 110
-----
9 <-- RESTO
4. 9 <-- DÍGITO VERIFICADOR
______________________________________________________
ALGORITMO 3, propiedades de la división por 11
1. Multiplicar cada dígito del RUT se por 9, 8, ..., 4, 9, 8, ... de atrás hacia adelante.
2. Sumar las multiplicaciones parciales.
3. Suma alternada de la lista reversa de los dígitos del resultado anterior.
4. El Dígito Verificador es el resultado anterior. Si es 10, se cambia por 'k'.
EJEMPLO. RUT: 11.222.333
1. 1 1 2 2 2 3 3 3 <-- RUT
* 8 9 4 5 6 7 8 9 <-- 9, 8, 7, 6, 5, 4, 9, 8, ...
--------------------------------------
8 9 8 10 12 21 24 27
2. SUMA: 8 + 9 + 8 + 10 + 12 + 21 + 24 + 27 = 119
3. SUMA ALTERNADA: 119 -> 9 - 1 + 1 = 9
4. 9 <-- DÍGITO VERIFICADOR
ActionScript
Nota del Autor:
El código devuelve un true o false solamente, el que la persona que diseñe tiene que asignar la
función que quiera. Usa dos campos de textos de input; uno de la pate numerica con la variable
"xRut" y otro con el campo del dígito verificador "Dv". Este código va directamente en el boton de
"aceptar" en el formulario en cuestión:
// Autor: Cristobal Brenner
on (release){
// Definicion de Variables Utilizadas
var Suma = 0;
var rut = xRut;
var NumMag = 2;
var Resto = 0;
// Defino el arreglo con los posibles digitos verificadores
var DigVer = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "K", "0");
var ParteNumerica = new Array();
// Valida que el rut no este vacio
if (rut.length == 0) { return false; }
// Copio solo la parte numerica, sin espacios ni puntos
// en otra variable para calcular el digito verificador
for (j=0, i=0; j<rut.length; j++)
{
if (rut.charAt(j) != ' ' && rut.charAt(j) != '.' && rut.charAt(j) != '-')
{
ParteNumerica[i] = rut.charAt(j);
++i;
}
}
// Se calcula el digito verificador del rut
for (i=ParteNumerica.length-1; i>=0; i--, NumMag++)
{
Suma += ParteNumerica[i]*NumMag;
trace(Suma +' '+ ParteNumerica[i] +' '+ NumMag);
if (NumMag>6) { NumMag = 1; }
}
Resto = 11-(Suma%11);
if (DigVer[Resto] != Dv.toUpperCase())
{
trace("Rut válido");
}
else
{
trace("Rut no válido");
}
}
ASP
' Autor: Rodolfo Barriga
Function codigo_veri(rut)
tur=strreverse(rut)
mult = 2
for i = 1 to len(tur)
if mult > 7 then mult = 2 end if
suma = mult * mid(tur,i,1) + suma
mult = mult +1
next
valor = 11 - (suma mod 11)
if valor = 11 then
codigo_veri = "0"
elseif valor = 10 then
codigo_veri = "k"
else
codigo_veri = valor
end if
end function
AWK
# Autor: Hernan Aburto
BEGIN{
T=ARGV[1];
v=1;
for(i=2;i<=9;i++)
{
if (i==8) v=2;
else v++;
S = S + v * (T%10);
T = int(T/10);
}
S = 11 - S%11;
if (S==10) {print "k";}
else if (S==11) print 0;
else print S;
}
Ejemplo de uso:
$ awk -f rut.awk 11111111
1
C
// Autor: ??
main(){int T,M=0,S=1;scanf("%d",&T);for(;T;T/=10)S=(S+T%10*(9-M++%6))%11;
printf("%c\n",S?S+47:75);}
C Sharp C#
// Autor: Alejandra Cruzat
private string digitoVerificador(int rut)
{
int Digito;
int Contador;
int Multiplo;
int Acumulador;
string RutDigito;
Contador = 2;
Acumulador = 0;
while (rut != 0)
{
Multiplo = (rut % 10) * Contador;
Acumulador = Acumulador + Multiplo;
rut = rut/10;
Contador = Contador + 1;
if (Contador ==
{
Contador = 2;
}
}
Digito = 11 - (Acumulador % 11);
RutDigito = Digito.ToString().Trim();
if (Digito == 10 )
{
RutDigito = "K";
}
if (Digito == 11)
{
RutDigito = "0";
}
return (RutDigito);
}
}
Clipper
' Autor: Andres Sepulveda
FUNCTION validarut(rut)
Local ext:=SUBSTR(rut,12,1)
local x:=0
local divisor:={3,2,7,6,5,4,3,2}
Local suma:=0
local vuelta := .F.
rut:=SUBSTR(rut,1,2)+SUBSTR(rut,4,3)+SUBSTR(rut,8,3)
if ext == "k"
ext:= "K"
endif
FOR x := 1 TO 8
suma += VAL(SUBSTR(rut,x,1))* divisor [x]
NEXT
suma := 11 - suma%11
if (suma == 10 .and. ext == "K") .OR. (suma == 11 .and. ext == "0")
vuelta=.T.
elseif suma == VAL(ext)
vuelta=.T.
endif
if vuelta==.T.
tone(7800,2)
else
tone(1800,2)
endif
RETURN (vuelta)
Cobol
* Autor: Laloco.Net ?
rutdig.
move spaces to ctrl
display nada line 10 position 57
accept rut-aux no beep
line 10 position 57
inspect rut-aux replacing leading " " by "0"
if numerostr is numeric and guion = "-"
move 0 to suma
move 2 to numerador
perform varying puntero-vector from 8 by -1
until puntero-vector = 0
compute suma = suma +
numeroval(puntero-vector) * numerador
add 1 to numerador
if numerador = 8 move 2 to numerador end-if
end-perform
divide suma by 11 giving entero remainder resto
compute dig = 11 - resto
if dig = 10
move "k" to digi2
else
if dig = 11
move "0" to digi2
end-if
end-if
if digito = "k"
move "k" to digito
end-if
if digito not = digi2
display spaces
line 10 position 57
display spaces line 10 position 60
display "digito no corresponde"
line 10 position 57 blink
accept nulo
display nada line 10 position 57
else
move rut-aux to rut-w
move "e" to ctrl
end-if
else
display spaces
line 10 position 57
display spaces line 10 position 62
display "Rut mal ingresado!!"
line 10 position 57 blink
accept nulo
display nada
line 10 position 57
end-if.
Delphi
// Autor: Gabriel Florit
Function ValRut(Rut: String):String;
var
Cuenta, Suma, totalrut, Revisa : Integer;
begin
Suma:=2;
TotalRut:=0;
For Cuenta:=Length(Trim(rut)) downto 1 do
begin
if Suma>7 then Suma:=2;
Totalrut:=Totalrut+((StrToInt(copy(rut,cuenta,1)))*suma);
Suma:=Suma+1;
end;
Revisa:=Round((frac(Totalrut/11)*10)+0.5);
Revisa:=11-revisa;
If Revisa=10 then Result:='K'
else
begin
If Revisa=11 then Result:='0'
else Result:=IntToStr(Revisa);
end;
end;
Excel
Function dv(a)
j = 2
For i = 0 To Len(a) - 1
aux = aux + Val(Mid$(a, Len(a) - i, 1)) * j
If j > 6 Then
j = 2
Else
j = j + 1
End If
Next i
aux1 = 11 - (aux Mod 11)
If aux1 < 10 Then
dv = aux1
Else
dv = "K"
End If
End Function
INTERCAL
DON'T BE FOOLED: THIS PROGRAM REALLY WORKS!!
It was written by Aldrin Martoq timed on 1046931060
This program is in the public domain
PLEASE DO ,1 <- #12
DO ,1 SUB #2 <- #28
DO ,1 SUB #1 <- #110
DO ,1 SUB #11 <- #128
DO ,1 SUB #3 <- #144
DO ,1 SUB #10 <- #160 (96)
PLEASE DO ,1 SUB #12 <- #206 (69)
DO (1550) NEXT
PLEASE STASH :1
PLEASE STASH :3
DO :1 <- :3
DO (1549) NEXT
PLEASE RETRIEVE :1
DO :2 <- :3
DO (1510) NEXT
DO :2 <- :3
PLEASE RETRIEVE :3
DO RESUME #1 (10)
PLEASE DO :2 <- #10
DO .1 <- .4
DO .2 <- #1
DO (1010) NEXT
DO .4 <- .3
DO (69) NEXT
DO :6 <- :3
DO :1 <- .4
DO (1549) NEXT
DO :1 <- :5
DO :2 <- :3
PLEASE DO (1509) NEXT
DO :5 <- :3
DO :1 <- :6
DO RESUME #1
PLEASE DO COME FROM (96)
DO ,1 SUB #9 <- #186
DO ,1 SUB #8 <- #162
DO ,1 SUB #7 <- #40
DO ,1 SUB #6 <- #216
DO ,1 SUB #5 <- #168
DO ,1 SUB #4 <- #152
DO READ OUT ,1
DO WRITE IN :1
PLEASE STASH :1
DO (18) NEXT
PLEASE DO RETRIEVE :1 (81)
DO READ OUT :1 + :3 (18)
PLEASE DO .4 <- #10
DO :5 <- #0
DO (10) NEXT
DO (10) NEXT
DO (10) NEXT
DO (10) NEXT
DO (10) NEXT
DO (10) NEXT
PLEASE DO .4 <- #10
DO (10) NEXT
DO (10) NEXT
DO :2 <- #11
DO :1 <- :5
DO (69) NEXT
DO :3 <- :2
DO RESUME #1
DO COME FROM (81)
DON'T UNDERSTAND THIS? Abandon all hope and just PLEASE GIVE UP
Java
// Autor: Luis Dujovne
class v{ public static void main(String args[]){int M=0,S=1,T=
Integer.parseInt(args[0]);for(;T!=0;T/=10)S=(S+T%10*(9-M++%6))%11;
System.out.println((char)(S!=0?S+47:75));}}
JavaScript
// Autor: Mannungo
function dv(T){var M=0,S=1;for(;T;T=Math.floor(T/10))
S=(S+T%10*(9-M++%6))%11;return S?S-1:'k';}
Maple
# Autor: Felipe Olmos
v:=proc(R) local M,S,T:M:=0:S:=1:for T from R while T>0 do
S:=(S+(T mod 10)*(9-(M mod 6)))mod 11:T:=floor((T-10)/10):M:=M+1:
od:
`if`(S>0,S-1,k):end proc;
OZ
%Programado por Rafael Meneses Osorio
declare
fun {DigitoVerificador RutSinVerificador}
fun {GetDigitos Rut}
if Rut>0 then
Rut mod 10|{GetDigitos Rut div 10}
else
nil
end
end
fun {Calcula Digitos C }
if Digitos == nil then
0
else
D Resto in
D|Resto=Digitos
((C mod 6)+2)* D+{Calcula Resto C+1}
end
end
R = 11- {Calcula {GetDigitos RutSinVerificador} 0} mod 11
in
case R of 10 then 'k'
[] 11 then 0
else R end
end
%ejemplo de Uso:
{Browse {DigitoVerificador 9872006}}
Pascal
{ Autor: Miguel Farah? }
Program DigitoVerificador;
Uses Crt;
Var s, d: String;
elFactor, i, a, digito, dummy: Integer;
PROCEDURE Input(mensaje: String; VAR numero: String);
VAR s: String; ch: Char;
ready: Boolean;
BEGIN
s:='';
ready:=FALSE;
Write(mensaje);
REPEAT
ch:=ReadKey;
CASE ch OF
'0': IF s='' THEN BEGIN
s:=ch;
Write(ch);
END ELSE IF (s<>'0') THEN BEGIN
s:=Concat(s,ch);
Write(ch);
END;
'1'..'9': IF (s='0') THEN BEGIN
s:=ch;
Write(#8, s);
END ELSE BEGIN
s:=Concat(s,ch);
Write(ch);
END;
#8: IF s<>'' THEN BEGIN { backspace elimina el último }
s:=Copy(s,1,Length(s)-1); { caracter del string
(siempre }
Write(#8,' ',#8); { que éste no sea vacío) }
END;
#13: IF (s='') THEN Write(#7) ELSE ready:=TRUE;
{ ENTER: listo para transformar a }
{ número, pero no acepta uno nulo }
ELSE ; { no hacer caso a ninguna otra tecla }
END; {case}
UNTIL ready;
Writeln;
numero:=s; { retornar el valor ingresado }
END;
FUNCTION Factor: Integer;
BEGIN
if ((elFactor<2) or (elFactor>7)) THEN BEGIN
writeln('ERROR EN LA EJECUCION DEL PROGRAMA - MEJOR ABORTO.');
Halt(1);
END ELSE BEGIN
elFactor:=elFactor+1;
IF (elFactor=8) THEN elFactor:=2;
END;
Factor:=elFactor;
END;
BEGIN
Writeln('Para finalizar, ingrese el RUT 0');
Writeln;
REPEAT
elFactor:=7; a:=0;
Input('Ingrese el RUT sin guión ni dígito verificador :', s);
FOR i:=Length(s) DOWNTO 1 DO BEGIN
d:=Copy(s,i,1);
Val(d,digito,dummy);
a:=a+digito*Factor;
END;
a:=11-(a MOD 11); IF (a=11) THEN a:=0;
write('El RUT ingresado es: ', s, '. El dígito verificador es: ');
IF (a<>10) THEN writeln(a) ELSE writeln('K');
writeln;
UNTIL (s='0');
END.
Perl
# Autor: Mannungo
sub dv{$_=pop;$r+=$&*(9-$c++%6)while s/\d$//;$r%11>9?k:$r%11;}
PHP
// Autor: Luis Dujovne
<?php
function dv($r){$s=1;for($m=0;$r!=0;$r/=10)$s=($s+$r%10*(9-$m++%6))%11;
return chr($s?$s+47:75);}
?>
PostgreSQL
' Autor: Andres Junge
CREATE OR REPLACE FUNCTION digito_verificador(varchar)
RETURNS char AS '
DECLARE
rut ALIAS FOR $1;
rut_cero varchar(8);
valor int;
BEGIN
valor := 0;
rut_cero := lpad(rut,8,''0'');
valor := valor + (substring(rut_cero,8,1)::int8)*2;
valor := valor + (substring(rut_cero,7,1)::int8)*3;
valor := valor + (substring(rut_cero,6,1)::int8)*4;
valor := valor + (substring(rut_cero,5,1)::int8)*5;
valor := valor + (substring(rut_cero,4,1)::int8)*6;
valor := valor + (substring(rut_cero,3,1)::int8)*7;
valor := valor + (substring(rut_cero,2,1)::int8)*2;
valor := valor + (substring(rut_cero,1,1)::int8)*3;
valor := valor % 11;
IF valor =1 THEN
RETURN ''K'';
END IF;
IF valor =0 THEN
RETURN ''0'';
END IF;
IF valor>1 AND valor<11 THEN
RETURN (11-valor)::char;
END IF;
END
' LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION valida_rut(varchar(9))
RETURNS bool AS '
DECLARE
rutfull ALIAS FOR $1;
rutfull_cero varchar(9);
rut varchar(8);
dv char;
BEGIN
IF rutfull IS NULL THEN
RETURN TRUE;
END IF;
rutfull_cero := lpad(rutfull,9,''0'');
rut:= substr(rutfull_cero,0,9);
dv := substr(rutfull_cero,9,1);
IF digito_verificador(rut)=upper(dv) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END
' LANGUAGE plpgsql;
Prolog
% Autor: Mannungo.
c([],0,1).
c([H|T],G,R):-c(T,F,S),R is (S+H*(9-F))mod 11,G is(F+1)mod 6.
dv(L,'k'):-c(L,_,0).
dv(L,R):-c(L,_,S),R is S-1.
Python
#!/usr/local/bin/python
# Autor: Daniel Bobadilla
M = 0
S = 1
T=input("")
while 1:
S = (S + (T % 10) * (9 - M%6)) % 11
M+=1
T/=10
if not(T): break
if (S):
print '',chr(S+47)
else:
print 'K'
Ruby
#!/usr/local/bin/ruby
# Digito rut verificador hecho en ruby (http://www.ruby-lang.org)
# Autor : Daniel Bobadilla Leal
# Usando la 1era version del Algortimo en palabras
# Uso ./ruby.rb
T=ARGV[0].to_i
v=1
S=0
for i in (2..9)
if i == 8
v=2
else v+=1
end
S+=v*(T%10)
T/=10
end
S = 11 - S%11
if S == 11
print 0, "\n"
elsif S == 10
print "K", "\n"
else
print S, "\n"
end
Scheme
;Programado por Rafael Meneses Osorio
;ej: >(verificador 55555555)
; >5
(define (verificador2 rutSinVerificador)
(let ((R
(- 11
(remainder
(let calculo ((restoRut rutSinVerificador) (c 0))
(let ((digito (remainder restoRut 10)))
(cond ((= restoRut 0) 0)
(else
(+ (* (+ (remainder c 6) 2) digito)
(calculo (/ (- restoRut digito) 10) (+ c 1)))))))
11))))
(cond ((= R 10) 'k)
((= R 11) 0)
(else R))))
SQL Server 2000
****** Author: Germán González ******/
/****** Object: Trigger dbo.verif_rut Script Date: 01/07/03 23:01:09 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[verif_rut]') and
OBJECTPROPERTY(id, N'IsTrigger') = 1)
drop trigger [dbo].[verif_rut]
GO
/****** Object: Trigger dbo.verif_rut Script Date: 01/07/03 23:01:34 ******/
/*** como se ve en el codigo el rut se saca del atributo rut_cli de la tabla cliente ***/
/*** hay que ingresar el rut completo sin punto y guion (. -)
/*** ejemplo: 12.345.678-9 se ingresaria: 123456789 ***/
/*** ejemplo: 9.876.543-2 se ingresaria: 098765432 (hay que ingresar el 0 ya que siempre son 9
numeros ***/
CREATE TRIGGER verif_rut
ON [dbo].[cliente]
FOR INSERT
AS
declare @valor int
declare @ruti char(9)
declare @dv char
set @ruti = (select rut_cli from inserted)
set @valor = 0
if (len(@ruti))=9
begin
set @valor = @valor + convert(int,substring(@ruti,8,1))*2
set @valor = @valor + convert(int,substring(@ruti,7,1))*3
set @valor = @valor + convert(int,substring(@ruti,6,1))*4
set @valor = @valor + convert(int,substring(@ruti,5,1))*5
set @valor = @valor + convert(int,substring(@ruti,4,1))*6
set @valor = @valor + convert(int,substring(@ruti,3,1))*7
set @valor = @valor + convert(int,substring(@ruti,2,1))*2
set @valor = @valor + convert(int,substring(@ruti,1,1))*3
set @valor = @valor % 11
if (@valor = 1)
begin
set @dv='k'
end
if @valor = 0
begin
set @dv='0'
end
if @valor>1 and @valor<11
begin
set @dv=str(11-@valor,1)
end
if @dv<>substring(@ruti,9,1)
begin
raiserror('verifique su rut',16,1)
rollback transaction
end
end
GO
s
Turing
% Autor: Mannungo
function dv( n : real ) : string
var aux, resultado : real
var valor : int
aux := n
resultado := 0
valor := 1
for i : 2 .. 9
if (i = then
valor := 2
else
valor := valor + 1
end if
resultado := resultado + valor * (aux mod 10)
aux := aux div 10
end for
resultado := 11 - ( resultado mod 11 )
if (resultado = 10) then
result "k"
else
result chr (round (resultado + 48))
end if
end dv
User-RPL, Calculadoras HP
Autor: German González
Solo hay que poner el numero en el stack y ejecutarlo.
<< ->STR { } SWAP DUP
SIZE 1 - 1 SWAP
FOR i DUP TAIL
SWAP HEAD ROT SWAP
OBJ-> + SWAP
NEXT OBJ-> + DUP
SIZE 7 ==
IF
THEN REVLIST 0 +
END
{ 2 3 4 5 6 7 2 3 } * OBJ-> DROP +
+ + + + + + 11 MOD
DUP 1 ==
IF
THEN "K"
ELSE DUP 0 ==
IF
THEN 0 DROP
ELSE 11 SWAP -
END
END
>>
Visual Basic - Visual Basic Aplicacion
Public Function RutDigito(ByVal Rut As Long) As String
Dim Digito As Integer
Dim Contador As Integer
Dim Multiplo As Integer
Dim Acumulador As Integer
Contador = 2
Acumulador = 0
While Rut <> 0
Multiplo = (Rut Mod 10) * Contador
Acumulador = Acumulador + Multiplo
Rut = Rut \ 10
Contador = Contador + 1
If Contador = 8 Then
Contador = 2
End If
Wend
Digito = 11 - (Acumulador Mod 11)
RutDigito = CStr(Digito)
If Digito = 10 Then RutDigito = "K"
If Digito = 11 Then RutDigito = "0"
End Function
Visual FoxPro
FUNCTION Val_Rut
PARAMETERS rut,digver
STORE 0 TO suma
STORE 2 TO j
Largo = LEN(rut)
FOR i = Largo TO 1 STEP -1
Dig = VAL(SUBSTR(rut,i,1))
suma = suma + (Dig * j)
IF j = 7
j = 1
ENDIF
j = j + 1
ENDFOR
RESTO = MOD(suma,11)
DO CASE
CASE RESTO = 0
dv = 0
CASE RESTO = 1
dv = "K"
IF digver = "k" OR digver = "K"
* WAIT 'RUT INCORRECTO!!!' WINDOWS
RETURN .F.
ENDIF
RETURN .T.
OTHERWISE
dv = 11 - RESTO
ENDCASE
IF digver == ALLTRIM(STR(dv))
RETURN .T.
ELSE
* WAIT 'RUT INCORRECTO!!!' WINDOWS
RETURN .F.
ENDIF
ENDFUNC
===========================