求購演算法源碼
『壹』 求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");
希望能夠幫助到你,望採納,謝謝!