My first blog.
The blog is intended to record something cause this editor
This blog will keep track with my ritual to read books.
I am now studying algorithm, and happily someone reccommend a book to me.
Introduction to the Design and Analysis of algorithms.
Try to describe in C forms.
This book at first give two examples for us to use.
Euclid’s algorithm:
Based on applying repeatedly the equality.
gcd(m,n)=gcd(n, m mod n). -----------(1)
Prove:
Denote the gcd as k, and the (1) equation is easy to see.
Step1: if n=0, return the value of m as the answer and stop, otherwise, procced to step 2
Step2: Divide m by n and assign the value of the remainder to r.
Step3:Assign the value of n to m and the value of r to n. Go to step 1.
This algorithm can also be transferred to help you solve some Polynomials’problems.
The complexity is O(log n).
Algorithm Sieve(n):
This kind of algorithm can simplify the regular process of finding prime numbers. Cause it costs much less complexity.
C code is given below:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int main(void){
int a[100],b[100];//below 100.
int n,p,j,i;
scanf("%d",&n);
for(p=2;p<n;p++) a[p]=p;
a[0]=a[1]=0;
for(p=2;p<=sqrt(n);p++){
if(a[p]!=0){
j=p*p;
while(j<=n){
a[j]=0;
j+=p;
}
}
}
i=0;
for(p=2;p<n;p++){
if(a[p]!=0){
b[i]=a[p];
i++;
}
}
for(int k=0;k<i;k++){
printf("%d ",b[k]);
}
printf("\n");
return 0;
}
If you want to save some spaces for your computer, you can form nodes to do the same work.
typedef struct node{
struct node* next;
int data;
}Node,*Pnode;
The comversion is easy.
I want to spot more lights to prove the code right.
Prove:
This is based on the process of delete prime numbers one by one.
First you need the scale of the number you want to input. For example, find the prime numbers below 100. So you get a list.
2 3 4 5 6 7 8 9 10 11…100
Firstly you will delete all the numbers having the “2” factor.
So you delete 4,6,8,10, and so on.
So you get the second list:
2 3 5 7 9 11 13…99
now you will continue the process by increase the factor’s value, 3, 5, 7, 11, and so on.
…
At last you will get the list of prime numbers below 100.
That’s because, if p is a prime number more than 2, and there must be some prime smaller than it. So at least when you use p as the factor to delete the numbers, 2p has already deleted when you use the 2 as the factor, so what you need to do is start it from pp, the square number of p, and add p to delete other factors.
here is the result( below 75):
PS D:\coding\.vscode\algorithm\intro\unit1> ./Sieve
75
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73
That’s all about this blog.