编程小工具

记录一些常用小工具(编程)

随机素数(指定范围)生成器

#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;
}

img

求逆元

基于扩展欧几里得算法

#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;
}

img

基于费马定理算法

#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;
}

img

计算时间差

引入头文件:
#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;
}

img

将字符串转为整数

在将字符串转十进制的过程中,若是较长的字符串,转的十进制比较大,下面按照如下公式,进行转换:
img

#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()
posted @ 2021-07-24 15:48  PamShao  阅读(192)  评论(0编辑  收藏  举报