Python/cryptography/extended_eucledian.ipynb

174 lines
3.4 KiB
Plaintext
Raw Normal View History

2024-11-20 22:52:43 +05:30
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "8561e0a7",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<style>.container{width:100%}</style>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%%HTML\n",
"<style>.container{width:100%}</style>"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "12f36b2f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"21"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def eucld_gcd(a,b):\n",
" if(a < b):\n",
" a , b = b , a\n",
" if(b==0):\n",
" return a\n",
" r = a%b\n",
" if(r==0):\n",
" return b\n",
" return eucld_gcd(b,r)\n",
"eucld_gcd(252,105)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "c060ee17",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, -48]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import numpy as np\n",
"def ext_eucld(a,b):\n",
" swap = False\n",
" if(a < b):\n",
" a , b = b , a\n",
" swap = True\n",
" def eucld(a,b):\n",
" if(b==0 or b==1):\n",
" return []\n",
" ls = []\n",
" while b!=1:\n",
" r = a%b\n",
" if(r==0):\n",
" return ls\n",
" idx = (a-r)//b\n",
" ls.append(idx)\n",
" a = b\n",
" b = r\n",
" return ls\n",
" \n",
" row = np.array([[1,0],[0,1]])\n",
" ls = eucld(a,b)\n",
" for i in ls:\n",
" row = np.append(row, [row[-2] - i*row[-1]] ,axis=0)\n",
" if(swap):\n",
" return list(row[-1])[::-1]\n",
" return list(row[-1])\n",
"ext_eucld(97,2)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "d3edd1f6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a=5, b=7, gcd=1, m=3, n=-2, ma+nb=1\n"
]
}
],
"source": [
"a = 5\n",
"b = 7\n",
"gcd = eucld_gcd(a,b)\n",
"m,n = ext_eucld(a,b)\n",
"print(f\"a={a}, b={b}, gcd={gcd}, m={m}, n={n}, ma+nb={m*a+n*b}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "782bb8d3",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "e224063e",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "63f1d5a4",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}