求购算法源码
‘壹’ 求BP神经网络算法的C++源代码
// AnnBP.cpp: implementation of the CAnnBP class.
//
//////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "AnnBP.h"
#include "math.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CAnnBP::CAnnBP()
{
eta1=0.3;
momentum1=0.3;
}
CAnnBP::~CAnnBP()
{
}
double CAnnBP::drnd()
{
return ((double) rand() / (double) BIGRND);
}
/*** 返回-1.0到1.0之间的双精度随机数 ***/
double CAnnBP::dpn1()
{
return (double) (rand())/(32767/2)-1;
}
/*** 作用函数,目前是S型函数 ***/
double CAnnBP::squash(double x)
{
return (1.0 / (1.0 + exp(-x)));
}
/*** 申请1维双精度实数数组 ***/
double* CAnnBP::alloc_1d_dbl(int n)
{
double *new1;
new1 = (double *) malloc ((unsigned) (n * sizeof (double)));
if (new1 == NULL) {
AfxMessageBox("ALLOC_1D_DBL: Couldn't allocate array of doubles\n");
return (NULL);
}
return (new1);
}
/*** 申请2维双精度实数数组 ***/
double** CAnnBP::alloc_2d_dbl(int m, int n)
{
int i;
double **new1;
new1 = (double **) malloc ((unsigned) (m * sizeof (double *)));
if (new1 == NULL) {
AfxMessageBox("ALLOC_2D_DBL: Couldn't allocate array of dbl ptrs\n");
return (NULL);
}
for (i = 0; i < m; i++) {
new1[i] = alloc_1d_dbl(n);
}
return (new1);
}
/*** 随机初始化权值 ***/
void CAnnBP::bpnn_randomize_weights(double **w, int m, int n)
{
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
w[i][j] = dpn1();
}
}
}
/*** 0初始化权值 ***/
void CAnnBP::bpnn_zero_weights(double **w, int m, int n)
{
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
w[i][j] = 0.0;
}
}
}
/*** 设置随机数种子 ***/
void CAnnBP::bpnn_initialize(int seed)
{
CString msg,s;
msg="Random number generator seed:";
s.Format("%d",seed);
AfxMessageBox(msg+s);
srand(seed);
}
/*** 创建BP网络 ***/
BPNN* CAnnBP::bpnn_internal_create(int n_in, int n_hidden, int n_out)
{
BPNN *newnet;
newnet = (BPNN *) malloc (sizeof (BPNN));
if (newnet == NULL) {
printf("BPNN_CREATE: Couldn't allocate neural network\n");
return (NULL);
}
newnet->input_n = n_in;
newnet->hidden_n = n_hidden;
newnet->output_n = n_out;
newnet->input_units = alloc_1d_dbl(n_in + 1);
newnet->hidden_units = alloc_1d_dbl(n_hidden + 1);
newnet->output_units = alloc_1d_dbl(n_out + 1);
newnet->hidden_delta = alloc_1d_dbl(n_hidden + 1);
newnet->output_delta = alloc_1d_dbl(n_out + 1);
newnet->target = alloc_1d_dbl(n_out + 1);
newnet->input_weights = alloc_2d_dbl(n_in + 1, n_hidden + 1);
newnet->hidden_weights = alloc_2d_dbl(n_hidden + 1, n_out + 1);
newnet->input_prev_weights = alloc_2d_dbl(n_in + 1, n_hidden + 1);
newnet->hidden_prev_weights = alloc_2d_dbl(n_hidden + 1, n_out + 1);
return (newnet);
}
/* 释放BP网络所占地内存空间 */
void CAnnBP::bpnn_free(BPNN *net)
{
int n1, n2, i;
n1 = net->input_n;
n2 = net->hidden_n;
free((char *) net->input_units);
free((char *) net->hidden_units);
free((char *) net->output_units);
free((char *) net->hidden_delta);
free((char *) net->output_delta);
free((char *) net->target);
for (i = 0; i <= n1; i++) {
free((char *) net->input_weights[i]);
free((char *) net->input_prev_weights[i]);
}
free((char *) net->input_weights);
free((char *) net->input_prev_weights);
for (i = 0; i <= n2; i++) {
free((char *) net->hidden_weights[i]);
free((char *) net->hidden_prev_weights[i]);
}
free((char *) net->hidden_weights);
free((char *) net->hidden_prev_weights);
free((char *) net);
}
/*** 创建一个BP网络,并初始化权值***/
BPNN* CAnnBP::bpnn_create(int n_in, int n_hidden, int n_out)
{
BPNN *newnet;
newnet = bpnn_internal_create(n_in, n_hidden, n_out);
#ifdef INITZERO
bpnn_zero_weights(newnet->input_weights, n_in, n_hidden);
#else
bpnn_randomize_weights(newnet->input_weights, n_in, n_hidden);
#endif
bpnn_randomize_weights(newnet->hidden_weights, n_hidden, n_out);
bpnn_zero_weights(newnet->input_prev_weights, n_in, n_hidden);
bpnn_zero_weights(newnet->hidden_prev_weights, n_hidden, n_out);
return (newnet);
}
void CAnnBP::bpnn_layerforward(double *l1, double *l2, double **conn, int n1, int n2)
{
double sum;
int j, k;
/*** 设置阈值 ***/
l1[0] = 1.0;
/*** 对于第二层的每个神经元 ***/
for (j = 1; j <= n2; j++) {
/*** 计算输入的加权总和 ***/
sum = 0.0;
for (k = 0; k <= n1; k++) {
sum += conn[k][j] * l1[k];
}
l2[j] = squash(sum);
}
}
/* 输出误差 */
void CAnnBP::bpnn_output_error(double *delta, double *target, double *output, int nj, double *err)
{
int j;
double o, t, errsum;
errsum = 0.0;
for (j = 1; j <= nj; j++) {
o = output[j];
t = target[j];
delta[j] = o * (1.0 - o) * (t - o);
errsum += ABS(delta[j]);
}
*err = errsum;
}
/* 隐含层误差 */
void CAnnBP::bpnn_hidden_error(double *delta_h, int nh, double *delta_o, int no, double **who, double *hidden, double *err)
{
int j, k;
double h, sum, errsum;
errsum = 0.0;
for (j = 1; j <= nh; j++) {
h = hidden[j];
sum = 0.0;
for (k = 1; k <= no; k++) {
sum += delta_o[k] * who[j][k];
}
delta_h[j] = h * (1.0 - h) * sum;
errsum += ABS(delta_h[j]);
}
*err = errsum;
}
/* 调整权值 */
void CAnnBP::bpnn_adjust_weights(double *delta, int ndelta, double *ly, int nly, double **w, double **oldw, double eta, double momentum)
{
double new_dw;
int k, j;
ly[0] = 1.0;
for (j = 1; j <= ndelta; j++) {
for (k = 0; k <= nly; k++) {
new_dw = ((eta * delta[j] * ly[k]) + (momentum * oldw[k][j]));
w[k][j] += new_dw;
oldw[k][j] = new_dw;
}
}
}
/* 进行前向运算 */
void CAnnBP::bpnn_feedforward(BPNN *net)
{
int in, hid, out;
in = net->input_n;
hid = net->hidden_n;
out = net->output_n;
/*** Feed forward input activations. ***/
bpnn_layerforward(net->input_units, net->hidden_units,
net->input_weights, in, hid);
bpnn_layerforward(net->hidden_units, net->output_units,
net->hidden_weights, hid, out);
}
/* 训练BP网络 */
void CAnnBP::bpnn_train(BPNN *net, double eta, double momentum, double *eo, double *eh)
{
int in, hid, out;
double out_err, hid_err;
in = net->input_n;
hid = net->hidden_n;
out = net->output_n;
/*** 前向输入激活 ***/
bpnn_layerforward(net->input_units, net->hidden_units,
net->input_weights, in, hid);
bpnn_layerforward(net->hidden_units, net->output_units,
net->hidden_weights, hid, out);
/*** 计算隐含层和输出层误差 ***/
bpnn_output_error(net->output_delta, net->target, net->output_units,
out, &out_err);
bpnn_hidden_error(net->hidden_delta, hid, net->output_delta, out,
net->hidden_weights, net->hidden_units, &hid_err);
*eo = out_err;
*eh = hid_err;
/*** 调整输入层和隐含层权值 ***/
bpnn_adjust_weights(net->output_delta, out, net->hidden_units, hid,
net->hidden_weights, net->hidden_prev_weights, eta, momentum);
bpnn_adjust_weights(net->hidden_delta, hid, net->input_units, in,
net->input_weights, net->input_prev_weights, eta, momentum);
}
/* 保存BP网络 */
void CAnnBP::bpnn_save(BPNN *net, char *filename)
{
CFile file;
char *mem;
int n1, n2, n3, i, j, memcnt;
double dvalue, **w;
n1 = net->input_n; n2 = net->hidden_n; n3 = net->output_n;
printf("Saving %dx%dx%d network to '%s'\n", n1, n2, n3, filename);
try
{
file.Open(filename,CFile::modeWrite|CFile::modeCreate|CFile::modeNoTruncate);
}
catch(CFileException* e)
{
e->ReportError();
e->Delete();
}
file.Write(&n1,sizeof(int));
file.Write(&n2,sizeof(int));
file.Write(&n3,sizeof(int));
memcnt = 0;
w = net->input_weights;
mem = (char *) malloc ((unsigned) ((n1+1) * (n2+1) * sizeof(double)));
// mem = (char *) malloc (((n1+1) * (n2+1) * sizeof(double)));
for (i = 0; i <= n1; i++) {
for (j = 0; j <= n2; j++) {
dvalue = w[i][j];
//fast(&mem[memcnt], &dvalue, sizeof(double));
fast(&mem[memcnt], &dvalue, sizeof(double));
memcnt += sizeof(double);
}
}
file.Write(mem,sizeof(double)*(n1+1)*(n2+1));
free(mem);
memcnt = 0;
w = net->hidden_weights;
mem = (char *) malloc ((unsigned) ((n2+1) * (n3+1) * sizeof(double)));
// mem = (char *) malloc (((n2+1) * (n3+1) * sizeof(double)));
for (i = 0; i <= n2; i++) {
for (j = 0; j <= n3; j++) {
dvalue = w[i][j];
fast(&mem[memcnt], &dvalue, sizeof(double));
// fast(&mem[memcnt], &dvalue, sizeof(double));
memcnt += sizeof(double);
}
}
file.Write(mem, (n2+1) * (n3+1) * sizeof(double));
// free(mem);
file.Close();
return;
}
/* 从文件中读取BP网络 */
BPNN* CAnnBP::bpnn_read(char *filename)
{
char *mem;
BPNN *new1;
int n1, n2, n3, i, j, memcnt;
CFile file;
try
{
file.Open(filename,CFile::modeRead|CFile::modeCreate|CFile::modeNoTruncate);
}
catch(CFileException* e)
{
e->ReportError();
e->Delete();
}
// printf("Reading '%s'\n", filename);// fflush(stdout);
file.Read(&n1, sizeof(int));
file.Read(&n2, sizeof(int));
file.Read(&n3, sizeof(int));
new1 = bpnn_internal_create(n1, n2, n3);
// printf("'%s' contains a %dx%dx%d network\n", filename, n1, n2, n3);
// printf("Reading input weights..."); // fflush(stdout);
memcnt = 0;
mem = (char *) malloc (((n1+1) * (n2+1) * sizeof(double)));
file.Read(mem, ((n1+1)*(n2+1))*sizeof(double));
for (i = 0; i <= n1; i++) {
for (j = 0; j <= n2; j++) {
//fast(&(new1->input_weights[i][j]), &mem[memcnt], sizeof(double));
fast(&(new1->input_weights[i][j]), &mem[memcnt], sizeof(double));
memcnt += sizeof(double);
}
}
free(mem);
// printf("Done\nReading hidden weights..."); //fflush(stdout);
memcnt = 0;
mem = (char *) malloc (((n2+1) * (n3+1) * sizeof(double)));
file.Read(mem, (n2+1) * (n3+1) * sizeof(double));
for (i = 0; i <= n2; i++) {
for (j = 0; j <= n3; j++) {
//fast(&(new1->hidden_weights[i][j]), &mem[memcnt], sizeof(double));
fast(&(new1->hidden_weights[i][j]), &mem[memcnt], sizeof(double));
memcnt += sizeof(double);
}
}
free(mem);
file.Close();
printf("Done\n"); //fflush(stdout);
bpnn_zero_weights(new1->input_prev_weights, n1, n2);
bpnn_zero_weights(new1->hidden_prev_weights, n2, n3);
return (new1);
}
void CAnnBP::CreateBP(int n_in, int n_hidden, int n_out)
{
net=bpnn_create(n_in,n_hidden,n_out);
}
void CAnnBP::FreeBP()
{
bpnn_free(net);
}
void CAnnBP::Train(double *input_unit,int input_num, double *target,int target_num, double *eo, double *eh)
{
for(int i=1;i<=input_num;i++)
{
net->input_units[i]=input_unit[i-1];
}
for(int j=1;j<=target_num;j++)
{
net->target[j]=target[j-1];
}
bpnn_train(net,eta1,momentum1,eo,eh);
}
void CAnnBP::Identify(double *input_unit,int input_num,double *target,int target_num)
{
for(int i=1;i<=input_num;i++)
{
net->input_units[i]=input_unit[i-1];
}
bpnn_feedforward(net);
for(int j=1;j<=target_num;j++)
{
target[j-1]=net->output_units[j];
}
}
void CAnnBP::Save(char *filename)
{
bpnn_save(net,filename);
}
void CAnnBP::Read(char *filename)
{
net=bpnn_read(filename);
}
void CAnnBP::SetBParm(double eta, double momentum)
{
eta1=eta;
momentum1=momentum;
}
void CAnnBP::Initialize(int seed)
{
bpnn_initialize(seed);
}
‘贰’ 求Pareto蚁群算法的源代码 java的
说明:信息素权重,路径权重和信息素蒸发率对最后的结果影响很大,需要微调。
目前发现2 / 5 / 0.5 能达到稍微让人满意的效果。本程序离完美的ACO还差很远,仅供参考。
本蚁群算法为AS算法。
用法:
1.new一个对象
ACOforTSP tsp = new ACPforTSP(tsp数据文件名,迭代次数,蚂蚁数量,信息素权重,路径权重,信息素蒸发率);
2.用go()方法运行
tsp.go();
ACOforTSP.java
___________________________________________________________________
import java.io.File;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
import static java.lang.Math.random;
import java.util.HashMap;
import java.io.FileReader;
import java.io.BufferedReader;
/**
*
* @author dvdface
*/
public class ACOforTSP {
//城市的距离表
private double[][] distance;
//距离的倒数表
private double[][] heuristic;
//启发信息表
private double[][] pheromone;
//权重
private int alpha, beta;
//迭代的次数
private int iterationTimes;
//蚂蚁的数量
private int numbersOfAnt;
//蒸发率
private double rate;
ACOforTSP (String file, int iterationTimes, int numbersOfAnt, int alpha, int beta, double rate) {
//加载文件
this.initializeData(file);
//初始化参数
this.iterationTimes = iterationTimes;
//设置蚂蚁数量
this.numbersOfAnt = numbersOfAnt;
//设置权重
this.alpha = alpha;
this.beta = beta;
//设置蒸发率
this.rate = rate;
}
private void initializeData(String filename) {
//定义内部类
class City {
int no;
double x;
double y;
City(int no, double x, double y) {
this.no = no;
this.x = x;
this.y = y;
}
private double getDistance(City city) {
return sqrt(pow((x - city.x), 2) + pow((y - city.y), 2));
}
}
try {
//定义HashMap保存读取的坐标信息
HashMap<Integer, City> map = new HashMap<Integer, City>();
//读取文件
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
for (String str = reader.readLine(); str != null; str = reader.readLine()) {
//将读到的信息保存入HashMap
if (str.matches("([0-9]+)(\\s*)([0-9]+)(.?)([0-9]*)(\\s*)([0-9]+)(.?)([0-9]*)")) {
String[] data = str.split("(\\s+)");
City city = new City(Integer.parseInt(data[0]),
Double.parseDouble(data[1]),
Double.parseDouble(data[2]));
map.put(city.no, city);
}
}
//分配距离矩阵存储空间
distance = new double[map.size() + 1][map.size() + 1];
//分配距离倒数矩阵存储空间
heuristic = new double[map.size() + 1][map.size() + 1];
//分配信息素矩阵存储空间
pheromone = new double[map.size() + 1][map.size() + 1];
for (int i = 1; i < map.size() + 1; i++) {
for (int j = 1; j < map.size() + 1; j++) {
//计算城市间的距离,并存入距离矩阵
distance[i][j] = map.get(i).getDistance(map.get(j));
//计算距离倒数,并存入距离倒数矩阵
heuristic[i][j] = 1 / distance[i][j];
//初始化信息素矩阵
pheromone[i][j] = 1;
}
}
} catch (Exception exception) {
System.out.println("初始化数据失败!");
}
}
class Ant {
//已访问城市列表
private boolean[] visited;
//访问顺序表
private int[] tour;
//已访问城市的个数
private int n;
//总的距离
private double total;
Ant() {
//给访问顺序表分配空间
tour = new int[distance.length+1];
//已存入城市数量为n,刚开始为0
n = 0;
//将起始城市1,放入访问结点顺序表第一项
tour[++n] = 1;
//给已访问城市结点分配空间
visited = new boolean[distance.length];
//第一个城市为出发城市,设置为已访问
visited[tour[n]] = true;
}
private int chooseCity() {
//用来random的随机数
double m = 0;
//获得当前所在的城市号放入j,如果和j相邻的城市没有被访问,那么加入m
for (int i = 1, j = tour[n]; i < pheromone.length; i++) {
if (!visited[i]) {
m += pow(pheromone[j][i], alpha) * pow(heuristic[j][i], beta);
}
}
//保存随机到的数
double p = m * random();
//寻找被随机到的城市
double k = 0;
//保存找到的城市
int q = 0;
for (int i = 1, j = tour[n]; k < p; i++) {
if (!visited[i]) {
k += pow(pheromone[j][i], alpha) * pow(heuristic[j][i], beta);
q = i;
}
}
return q;
}
private void constructSolution () {
while (n != (distance.length-1) ) {
//选取下一个城市
int p = chooseCity();
//计算总的距离
total += distance[tour[n]][p];
//将选取到的城市放入已访问列表
tour[++n] = p;
//将选取到的城市标记为已访问
visited[p] = true;
}
//回到起点
total += distance[tour[1]][tour[n]];
//将起点加入访问顺序表的最后
tour[++n] = tour[1];
}
private void releasePheromone() {
//释放信息素的大小
double t = 1/total;
//释放信息素
for (int i=1;i<tour.length-1;i++) {
pheromone[tour[i]][tour[i+1]] += t;
pheromone[tour[i+1]][tour[i]] += t;
}
}
}
public void go() {
//保存最好的路径和路径长度
double bestTotal = Double.MAX_VALUE;
int[] bestTour = new int[distance.length+1];
//新建蚂蚁数组,用来引用所创建的蚂蚁
Ant[] ant = new Ant[numbersOfAnt];
//进行iterationTimes次迭代
while (iterationTimes != 0) {
//初始化新的一批蚂蚁(这里用构造新的蚂蚁代替重置蚂蚁状态)
for (int i=0; i<numbersOfAnt; i++) {
ant[i] = new Ant();
}
//进行一次迭代(即让所有的蚂蚁构建一条路径)
for (int i=0; i<numbersOfAnt; i++) {
ant[i].constructSolution();
//如果蚂蚁构建的路径长度比上次最好的还好,那么保存这个长度和它所走的路径
if (ant[i].total<bestTotal) {
bestTotal = ant[i].total;
System.array(ant[i].tour, 1, bestTour, 1, bestTour.length-1);
}
}
//蒸发信息素
evaporatePheromone();
//释放信息素
for (int i=0; i<numbersOfAnt; i++) {
ant[i].releasePheromone();
}
//报告本次迭代的信息
System.out.format("本次为倒数第%d次迭代,当前最优路径长度为%10.2f\n",iterationTimes,bestTotal);
//迭代总数减去1,进行下次迭代
iterationTimes--;
}
//输出最好的路径长度
System.out.format("得到的最优的路径长度为:%10.2f\n",bestTotal);
//输出最好的路径
System.out.println("最优路径如下:");
for (int i=1; i<bestTour.length; i++) {
System.out.print("→"+bestTour[i]);
}
}
private void evaporatePheromone() {
for (int i = 1; i < pheromone.length; i++)
for (int j = 1; j < pheromone.length; j++) {
pheromone[i][j] *= 1-rate;
}
}
}
‘叁’ 求RSA 的C++源代码 !谢谢!
请注意保存,以防失效,如果帮到你,请采纳
‘肆’ 急求 MD5的加密解密算法,用C++实现的源代码 高分答谢
要代码,还是要相关的解释资料?
---------------------------------
要代码的话:
两个文件:
--------------------------
1. md5.h:
#pragma once
typedef unsigned long int UINT32;
typedef unsigned short int UINT16;
/* MD5 context. */
typedef struct {
UINT32 state[4]; /* state (ABCD) */
UINT32 count[2]; /* number of bits, molo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
} MD5_CTX;
void MD5Init (MD5_CTX *);
void MD5Update (MD5_CTX *, unsigned char *, unsigned int);
void MD5Final (unsigned char [16], MD5_CTX *);
--------------------------
2. md5.cpp:
#include "md5.h"
#include "memory.h"
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
static void MD5Transform (UINT32 a[4], unsigned char b[64]);
static void Encode (unsigned char *, UINT32 *, unsigned int);
static void Decode (UINT32 *, unsigned char *, unsigned int);
static unsigned char PADDING[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (UINT32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (UINT32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (UINT32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (UINT32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
void MD5Init (MD5_CTX *context)
{
context->count[0] = context->count[1] = 0;
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
void MD5Update (MD5_CTX *context, unsigned char *input, unsigned int inputLen)
{
unsigned int i, index, partLen;
index = (unsigned int)((context->count[0] >> 3) & 0x3F);
if ((context->count[0] += ((UINT32)inputLen << 3))
< ((UINT32)inputLen << 3))
context->count[1]++;
context->count[1] += ((UINT32)inputLen >> 29);
partLen = 64 - index;
if (inputLen >= partLen) {
memcpy((unsigned char *)&context->buffer[index], (unsigned char *)input, partLen);
MD5Transform (context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD5Transform (context->state, &input[i]);
index = 0;
}
else
i = 0;
memcpy((unsigned char *)&context->buffer[index], (unsigned char *)&input[i],
inputLen-i);
}
void MD5Final (unsigned char digest[16], MD5_CTX * context)
{
unsigned char bits[8];
unsigned int index, padLen;
Encode (bits, context->count, 8);
index = (unsigned int)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
MD5Update (context, PADDING, padLen);
MD5Update (context, bits, 8);
Encode (digest, context->state, 16);
memset ((unsigned char *)context, 0, sizeof (*context));
}
static void MD5Transform (UINT32 state[4], unsigned char block[64])
{
UINT32 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode (x, block, 64);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
memset ((unsigned char *)x, 0, sizeof (x));
}
static void Encode (unsigned char *output, UINT32 *input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (unsigned char)(input[i] & 0xff);
output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
}
}
static void Decode (UINT32 *output, unsigned char *input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((UINT32)input[j]) | (((UINT32)input[j+1]) << 8) |
(((UINT32)input[j+2]) << 16) | (((UINT32)input[j+3]) << 24);
}
--------------------------
就这两个文件。使用的时候把它们加入工程或者makefile,调用时包含md5.h即可,给个简单的例子,输入一个字符串然后计算它的md5值并输出,在VC6.0和GCC4.4下测试通过:
#include <stdio.h>
#include <string.h>
#include "md5.h"
int main ()
{
char tmp[128];
unsigned char digest[16];
MD5_CTX context;
scanf("%s",tmp);
MD5Init (&context);
MD5Update (&context, (unsigned char*)tmp, strlen(tmp));
MD5Final (digest,&context);
printf("MD5Value:");
for(int i=0; i<16; ++i)
{
printf("%02X",digest[i]);
}
printf("\n");
return 0;
}
‘伍’ 求RSA算法的源代码(c语言)
这个是我帮个朋友写的,写的时候发现其实这个没那么复杂,不过,时间复杂度要高于那些成型了的,为人所熟知的rsa算法的其他语言实现.
#include
int
candp(int
a,int
b,int
c)
{
int
r=1;
b=b+1;
while(b!=1)
{
r=r*a;
r=r%c;
b--;
}
printf("%d",r);
return
r;
}
void
main()
{
int
p,q,e,d,m,n,t,c,r;
char
s;
{printf("input
the
p:\n");
scanf("%d\n",&p);
printf("input
the
q:\n");
scanf("%d%d\n",&p);
n=p*q;
printf("so,the
n
is
%3d\n",n);
t=(p-1)*(q-1);
printf("so,the
t
is
%3d\n",t);
printf("please
intput
the
e:\n");
scanf("%d",&e);
if(e<1||e>t)
{printf("e
is
error,please
input
again;");
scanf("%d",&e);}
d=1;
while
(((e*d)%t)!=1)
d++;
printf("then
caculate
out
that
the
d
is
%5d",d);
printf("if
you
want
to
konw
the
cipher
please
input
1;\n
if
you
want
to
konw
the
plain
please
input
2;\n");
scanf("%d",&r);
if(r==1)
{
printf("input
the
m
:"
);/*输入要加密的明文数字*/
scanf("%d\n",&m);
c=candp(m,e,n);
printf("so
,the
cipher
is
%4d",c);}
if(r==2)
{
printf("input
the
c
:"
);/*输入要解密的密文数字*/
scanf("%d\n",&c);
m=candp(c,d,n);
printf("so
,the
cipher
is
%4d\n",m);
printf("do
you
want
to
use
this
programe:yes
or
no");
scanf("%s",&s);
}while(s=='y');
}
}
‘陆’ 计算机图形学:线段剪裁中点分割算法,要求用C++做,急求源代码啊,谢谢! 752512212
#include <GL/glut.h>#include <stdlib.h>#include "iostream.h"int x0,y0,x1,y1;int Max(int a,int b,int c){ if(a>b) { if(a>c) return a; else return c; } else { if(b>c) return b; else return c; }}int Min(int a,int b,int c){ if(a<b) { if(a<c) return a; else return c; } else { if(b<c) return b; else return c; }}void DrawLine1(int x0,int y0,int x1,int y1){ int d,temp; temp=y0; d=2*(y1-y0)-(x1-x0); glBegin(GL_POINTS); glVertex2d(x0,y0); glEnd(); for(int k=x0+1;k<x1;k++) { if(d>=0) { glBegin(GL_POINTS); glVertex2d(k,temp+1); glEnd(); d=d+2*(y1-y0)-2*(x1-x0); temp=temp+1; } else { glBegin(GL_POINTS); glVertex2d(k,temp); glEnd(); d=d+2*(y1-y0); temp=temp; } } glBegin(GL_POINTS); glVertex2d(x1,y1); glEnd();}void DrawLine2(int x0,int y0,int x1,int y1){ int d,temp; temp=x0; d=2*(x1-x0)-(y1-y0); glBegin(GL_POINTS); glVertex2d(x0,y0); glEnd(); for(int k=y0+1;k<y1;k++) { if(d>=0) { glBegin(GL_POINTS); glVertex2d(temp+1,k); glEnd(); d=d+2*(x1-x0)-2*(y1-y0); temp=temp+1; } else { glBegin(GL_POINTS); glVertex2d(temp,k); glEnd(); d=d+2*(x1-x0); temp=temp; } } glBegin(GL_POINTS); glVertex2d(x1,y1); glEnd();}void DrawTriangle(int x0,int y0,int x1,int y1,int x2,int y2){ int xmin,xmax,ymin,ymax; float a,b,c; xmin=Min(x0,x1,x2); xmax=Max(x0,x1,x2); ymin=Min(y0,y1,y2); ymax=Max(y0,y1,y2); glColor3f(1.0f,0.0f,0.0f); glBegin(GL_POINTS); glVertex2d(x0,y0); glEnd(); glColor3f(0.0f,1.0f,0.0f); glBegin(GL_POINTS); glVertex2d(x1,y1); glEnd(); glColor3f(0.0f,0.0f,1.0f); glBegin(GL_POINTS); glVertex2d(x2,y2); glEnd(); for(float n=ymin;n<=ymax;n++) for(float m=xmin;m<xmax;m++) { a=((y1-y2)*m+(x2-x1)*n+x1*y2-x2*y1)/((y1-y2)*x0+(x2-x1)*y0+x1*y2-x2*y1); b=((y2-y0)*m+(x0-x2)*n+x2*y0-x0*y2)/((y2-y0)*x1+(x0-x2)*y1+x2*y0-x0*y2); c=((y0-y1)*m+(x1-x0)*n+x0*y1-x1*y0)/((y0-y1)*x2+(x1-x0)*y2+x0*y1-x1*y0); if(a>0 && b>0 && c>0) { float color0=a*1.0; float color1=b*1.0; float color2=c*1.0; glColor3f(color0,color1,color2); glBegin(GL_POINTS); glVertex2d(m,n); glEnd(); } } }void display(){/* clear all pixels */ glClear (GL_COLOR_BUFFER_BIT); glColor3f (1.0, 1.0, 1.0); glBegin(GL_POINTS); glVertex2d(x,y); 中间是点的坐标 glEnd(); */ /*下面的语句是画一个白色的正方形*/ if((y1-y0)/(x1-x0)<=1) { DrawLine1(x0,y0,x1,y1); } else { DrawLine2(x0,y0,x1,y1); } DrawTriangle(35,35,135,185,235,35);/* don't wait! * start processing buffered OpenGL routines */ glFlush ();}void init (void) {/* select clearing color */ glClearColor (0.0, 0.0, 0.0, 0.0);/* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, 600, 0, 600);}/* * Declare initial window size, position, and display mode * (single buffer and RGBA). Open window with "hello" * in its title bar. Call initialization routines. * Register callback function to display graphics. * Enter main loop and process events. */int main(int argc, char** argv){ cout<<"input x0,y0,x1,y1 :"<<endl; cin>>x0>>y0>>x1>>y1; glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); //设置窗口大小,以像素为单位 glutInitWindowSize (600, 600); glutInitWindowPosition (100, 100); glutCreateWindow ("hello");
希望能够帮助到你,望采纳,谢谢!