Signed-off-by: Marcin Woźniak <y0rune@aol.com>
This commit is contained in:
Marcin Woźniak 2020-11-08 23:33:06 +01:00
parent 63e97d3f52
commit d2816f13ea
Signed by: y0rune
GPG Key ID: F204C385F57EB348

View File

@ -27,22 +27,6 @@ end
## Zad. 1.1 ## Zad. 1.1
def random_gen_Zn(n,k) def random_gen_Zn(n,k)
#b = k.to_s(2).count "[0-1]"
#r = SecureRandom.random_number(n)
#x = r.to_s(2).count "[0-1]"
#until x != b do
# #if r < n then
# r = SecureRandom.random_number(n)
# x = r.to_s(2).count "[0-1]"
# puts r
# puts x
# #end
#end
#return r
if 2**(k-1) < n && k > 0 then if 2**(k-1) < n && k > 0 then
if k == 1 then if k == 1 then
min = 0 min = 0
@ -52,43 +36,44 @@ def random_gen_Zn(n,k)
max = (2**k)-1 max = (2**k)-1
end end
end end
while true do
r = rand(min..max) r = rand(min..max)
while true do if r < n then
ra = rand(min..max) break
if ra < n then end
break end
end
end
return ra return ra
end end
## Zad. 1.2 ## Zad. 1.2
def reciprocal_Phi_n(n,b) def reciprocal_Phi_p(n,p)
u = extended_euklides(n,b)[0] # n mod p
v = extended_euklides(n,b)[1] u = extended_euklides(n,p)[0]
v = extended_euklides(n,p)[1]
if v % n == 0 then if u * n % p == 1
return v puts u
else else
return u puts v
end end
end end
## Zad. 1.3 ## Zad. 1.3
def betterExponentiation(x,k,n) def betterExponentiation(x,k,n)
b = x.to_s(2) b = k.to_s(2).reverse
l = b.count "[0-1]" l = b.count "[0-1]"
y = 1 y = 1
i = l - 1 i = l - 1
for j in 1..i while i >= 0
y = y**2 % n y = y**2 % n
if b[-1*(j)] if b[i]=="1" then
y = y * x % n y = y * x % n
end end
i = i - 1
end end
return y return y
end end
@ -97,7 +82,7 @@ end
def remSqEuler(a,p) def remSqEuler(a,p)
ans = betterExponentiation(a,(p-1)/2,p) ans = betterExponentiation(a,(p-1)/2,p)
if ans > 0 && Prime.prime?(p) then if ans == 1 && Prime.prime?(p) then
return true return true
else else
return false return false
@ -105,18 +90,43 @@ def remSqEuler(a,p)
end end
## Zad. 1.5 ## Zad. 1.5
def squareRootFp(a) def squareRootFp(p,b)
p = 3 % 4 if p % 4 == 3 && remSqEuler(p,b) == true then
if remSqEuler(a,p) then for i in 1..p
bp = betterExponentiation(a,(p+1)/4,4) % 4 a = betterExponentiation(i, (p+1)/4, p)
bm = -1 * bp #puts i.inspect + " " + a.inspect + "=" + b.inspect
return bp,bm if a == b then
puts i
break
end
end
end end
end end
#puts extended_euklides(10,13) ## Zad. 1.6
puts random_gen_Zn(50,3) def primalityTest(n)
#puts reciprocal_Phi_n(10,13) if n == 1 then
#puts betterExponentiation(112218876,2,10) return false
#puts remSqEuler(3,13) end
#puts squareRootFp(13)
if n == 2 || n == 3 then
return true
end
counter = rand(n/2..n)
while (counter != 0) do
b = rand(2..n)
if betterExponentiation(b,n-1,n) != 1 then
return false
end
counter = counter + 1
end
return true
end
#1 #puts random_gen_Zn(50,3)
#2 #puts reciprocal_Phi_p(5,7)
#3 #puts betterExponentiation(24637864786278436723,10,3)
#4 #puts remSqEuler(5,13)
#5 #puts squareRootFp(7,2)
#6 #puts primalityTest(10)