編程小工具
記錄一些常用小工具(編程)
隨機素數(指定范圍)生成器
#define _CRT_SECURE_NO_WARNINGS
#include stdio.h
#include stdlib.h
#include time.h
#define randomInt(a,b) (rand()%(b-a)+a)
int prime(int n)
{
int i;
if (n 2) {
return -1;
}
else {
for (i = 2; i n; i++) {//判斷n在2~n-1中有沒有因數
if (n % i == 0)//如果用可以除盡的數,則非素數
break;
}
if (i n) {//存在2~n-1之間有因數
return -1;
}
else
return 0;
}
return 0;
}
int main()
{
int k,res,a,b;
printf("-------------素數生成器--------------\n");
printf(" 輸入范圍:[a,b)\n");
printf("-------------------------------------\n");
int ntime = 20;
while (ntime 0)
{
scanf("%d %d", &a, &b);
srand((unsigned)time(NULL));
do
{
res = randomInt(a, b);
k = prime(res);
} while (k == -1);
printf("素數:%d\n", res);
ntime--;
printf("還有%d次!\n",ntime - 1);
}
system("pause");
return 0;
}

求逆元
基于擴展歐幾里得算法
#define _CRT_SECURE_NO_WARNINGS
#include stdio.h
#include stdlib.h
int exgcd(int a, int b, int& x, int& y)//擴展歐幾里得算法
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
int ret = exgcd(b, a % b, y, x);
y -= a / b * x;
return ret;
}
int getInv(int a, int mod)//求a在mod下的逆元,不存在逆元返回-1
{
int x, y;
int d = exgcd(a, mod, x, y);
return d == 1 ? (x % mod + mod) % mod : -1;
}
int main() {
int m, n;
puts(" 擴展歐幾里得求逆元\n");
puts(" 對m * x = 1 mod n,求x\n");
printf("請輸入m=");
scanf("%d", &m);
printf("請輸入n=");
scanf("%d", &n);
printf("x=%d\n", getInv(m, n));
system("pause");
return 0;
}

基于費馬定理算法
#define _CRT_SECURE_NO_WARNINGS
#include stdio.h
#include math.h
int main()
{
int m, n, x;
puts(" 基于費馬定理求逆元\n");
puts(" 對m * x = 1 mod n,求x\n");
printf("請輸入m=");
scanf("%d", &m);
printf("請輸入n=");
scanf("%d", &n);
x = (int)pow(m, n - 2) % n;
printf("x=%d\n", x);
system("pause");
return 0;
}

計算時間差
引入頭文件:
#include time.h
給出定義變量:
time_t begin, end;
前后分別寫:
begin = clock();
....
end = clock();
printf("\n\t\t\t加密時間: %f seconds\n", (double)(end - begin) / CLOCKS_PER_SEC);
ElGamal算法中素數的生成元
使用大數庫
#includestdio.h
#includestdlib.h
#include "miracl.h"
#include time.h
time_t begin, end;
int main()
{
int MAX_D=0;
miracl* mip = mirsys(MAX_D + 10, 10);
big p = mirvar(0);
big p_1 = mirvar(0);//p-1
big p_2 = mirvar(0);//p-2
big q = mirvar(0);
big g = mirvar(0);
big flag = mirvar(0);//中間變量
big one = mirvar(1);//常量1
printf("----------------------------\n\n");
printf(" 素數生成元\n\n");
printf("----------------------------\n\n");
printf("請輸入生成素數的位數:");
scanf("%d", &MAX_D);
//密鑰生成部分
{
irand((unsigned)time(NULL)); // 使用當前時間作為隨機數種子
//隨機生成一個安全素數p
bigdig(MAX_D, 10, q);//生成一個150位的隨機數
nxsafeprime(0, 0, q, p);//生成一個比q大的安全素數p
copy(p, q);
decr(q, 1, q);
subdiv(q, 2, q);//生成q=(p-1)/2
decr(p, 1, p_1);//生成p_1=p-1
decr(p, 2, p_2);//生成p_2=p-2
//尋找一個本原根
//irand((unsigned)time(NULL)); // 使用當前時間作為隨機數種子
while (1)
{
bigrand(p_1, g);//g小于p-1
if (compare(g, one) = 0)//保證g大于1
continue;
powmod(g, mirvar(2), p, flag);
if (compare(flag, one) != 0)
{
powmod(g, q, p, flag);
if (compare(flag, one) != 0)
{
multiply(q, mirvar(2), flag);
powmod(g, flag, p, flag);
if (compare(flag, one) == 0)
break;
}
}
}//end
printf("p = ");
cotnum(p, stdout);
printf("g = ");
cotnum(g, stdout);
}
mirexit();
system("pause");
return 0;
}

將字符串轉為整數
在將字符串轉十進制的過程中,若是較長的字符串,轉的十進制比較大,下面按照如下公式,進行轉換:

#include stdio.h
#include stdlib.h
#include string.h
#include ctype.h
#define pow_2(n) (1n) //計算2的n次方
/* 十六進制字符轉換成整數 */
/*
* 將字符轉換為數值
* */
int c2i(char ch)
{
// 如果是數字,則用數字的ASCII碼減去48, 如果ch = '2' ,則 '2' - 48 = 2
if(isdigit(ch))
return ch - 48;
// 如果是字母,但不是A~F,a~f則返回
if( ch 'A' || (ch 'F' && ch 'a') || ch 'z' )
return -1;
// 如果是大寫字母,則用數字的ASCII碼減去55, 如果ch = 'A' ,則 'A' - 55 = 10
// 如果是小寫字母,則用數字的ASCII碼減去87, 如果ch = 'a' ,則 'a' - 87 = 10
if(isalpha(ch))
return isupper(ch) ? ch - 55 : ch - 87;
return -1;
}
/*
* 功能:將十六進制字符串轉換為整型(int)數值
* */
int hex2dec(char *hex)
{
int len;
int num = 0;
int temp;
int bits;
int i;
// 此例中 hex = "1de" 長度為3, hex是main函數傳遞的
len = strlen(hex);
for (i=0, temp=0; ilen; i++, temp=0)
{
// 第一次:i=0, *(hex + i) = *(hex + 0) = '1', 即temp = 1
// 第二次:i=1, *(hex + i) = *(hex + 1) = 'd', 即temp = 13
// 第三次:i=2, *(hex + i) = *(hex + 2) = 'd', 即temp = 14
temp = c2i( *(hex + i) );
// 總共3位,一個16進制位用 4 bit保存
// 第一次:'1'為最高位,所以temp左移 (len - i -1) * 4 = 2 * 4 = 8 位
// 第二次:'d'為次高位,所以temp左移 (len - i -1) * 4 = 1 * 4 = 4 位
// 第三次:'e'為最低位,所以temp左移 (len - i -1) * 4 = 0 * 4 = 0 位
//bits = (len - i - 1) * 4;
//temp = temp bits;
num+=pow_2(i)*temp;
// 此處也可以用 num += temp;進行累加
//num = num | temp;
}
// 返回結果
return num;
}
int main(void)
{
char *ch="abc123";
printf("%d\n", hex2dec(ch));
system("pause");
return 0;
}
生成隨機數
#include time.h
/*
生成隨機數
取得[0,x)的隨機整數:rand()%x;
取得[0,x]的隨機整數:rand()%(x+1);
取得[a,b)的隨機整數:rand()%(b-a)+a;
取得(a,b]的隨機整數:rand()%(b-a)+a+1;
取得[a,b]的隨機整數:rand()%(b-a+1)+a;
取得0-1之間的浮點數:rand()/double(RAND_MAX)
*/
int rand_n(int p)
{
return rand()%p;
}
int main()
{
int i=0;
srand((unsigned)time(0));
for(i;i5;i++)
{
printf("%d\n",rand_n(5));
}
system("pause");
return 0;
}
數據庫
清空CSV文件中的空表
'''
清除CSV數據表中的空表
'''
import os,csv
def main():
path = 'D:\\work\\8.21\\demo\\DB_SCV\\mpzy'
files = os.listdir(path)
for file in files:
total = len(open(os.path.join(path, file), 'r', encoding='utf-8').readlines())
if total <= 2:
os.remove(os.path.join(path, file))
print(file,",delect!")
else:continue
print("null clean,ok!")
if __name__ == "__main__":
main()
清空mysql中的空表
'''
清除mysql數據庫中的空表
'''
import pymysql
# 刪除指定的表
def delete_table(cursor, tabls_name):
cursor.execute("drop table %s" % tabls_name)
# 判斷表是否為空表
def judge_null(cursor, tabls_name):
cursor.execute("SELECT COUNT(*) FROM %s" % tabls_name)
count_wm = cursor.fetchall()
return count_wm[0][0] # 返回表的數據行數
# 列出所有的表
def list_table(cursor):
cursor.execute("show tables")
table_list = [tuple[0] for tuple in cursor.fetchall()]
return table_list
def main():
db = pymysql.connect(host='localhost',user='root',password='root',database='gallant')
cursor = db.cursor()
tables = list_table(cursor)
for table in tables:
if judge_null(cursor, table) == 0:
delete_table(cursor, table)
print(table,",ok!")
else:continue
print("mysql clean null,ok!")
if __name__ == "__main__":
main()
獲取mysql中的所有主鍵信息
'''
連接mysql,獲取表結構,查找主鍵字段和值
'''
import pymysql
# 獲取數據庫表的主鍵
def get_key(cursor,table):
cursor.execute('desc %s' % table)
count_wm = cursor.fetchall()
for i in count_wm:
if 'PRI' in i:
return i[0]
# 列出所有的表
def list_table(cursor):
cursor.execute("show tables")
table_list = [tuple[0] for tuple in cursor.fetchall()]
return table_list
# 獲取指定表和字段的值
def get_values(cursor,table,colm):
cursor.execute("select {} from {}".format(colm,table))
colm_value = ()
for tuple in cursor.fetchall():
colm_value = colm_value.__add__(tuple)
return list(colm_value) # 列表形式返回值
def main():
db = pymysql.connect(host='localhost', user='root', password='root', database='gallant')
cursor = db.cursor()
table_list = list_table(cursor) # 獲取所有表名
for table in table_list:
key = get_key(cursor,table) # 獲取表中主鍵
key_values = get_values(cursor, table, key) # 獲取主鍵中的值
print(key,key_values)
if __name__ == '__main__':
main()
獲取mysql中的表名和字段名
'''
獲取mysql數據庫中的表名和字段名,格式為:{"admin_user": ["member_id", "name", "mobile"]}
'''
import json
import pymysql
# 查詢所有字段
def list_col(cursor, tabls_name):
cursor.execute("select * from %s" % tabls_name)
col_name_list = [tuple[0] for tuple in cursor.description]
return col_name_list
# 列出所有的表
def list_table(cursor):
cursor.execute("show tables")
table_list = [tuple[0] for tuple in cursor.fetchall()]
return table_list
def get_tables():
db = pymysql.connect(host='localhost',user='root',password='root',database='sqllit')
cursor = db.cursor()
tables_dict = {}
tables = list_table(cursor) # 獲取所有表,返回的是一個可迭代對象
print("表名:",tables)
for table in tables:
col_names = list_col(cursor, table)[1:]
tables_dict[table]=col_names
db.close()
return tables_dict # 輸出所有字段名
def main():
data = json.dumps(get_tables())
print("{表名:字段名}:",data)
if __name__ == "__main__":
main()

浙公網安備 33010602011771號