"Data Structure and Algorithm (DSACPP)" study notes (1): preface supplement

Algorithm is poor

Insert picture description here

/* 
Hailstone序列,也叫做3n+1序列,问题如下:
(1)输入一个正整数n;
(2)如果n=1则结束;
(3)如果n是奇数,则n变为3n+1,否则n变为n/2;
Hailstone序列的特殊之处在于:尽管很容易将这个问题讲清楚,但直到今天仍不能保证这个问题的算法对所有可能的输入都有效——即至今没有人证明对所有的正整数该过程都终止。
*/

#include <stdio.h>
int hailstone( int n ) {
	int length = 1;
	while ( 1 < n ) {
	  printf("%d ", n);
	  
	  if ( n % 2)  n = 3*n + 1;
	  else n /= 2;
	  length++; 
	}
	
	printf("\n\n");
	return length;
}

int main() {
	hailstone(42);
	hailstone(7);
	hailstone(27);
	
	return 0;
}

Insert picture description here

TM running example

Insert picture description here
Insert picture description here

(<,1;0,L,<): 当前状态为<,且当前字符为1,则将当前字符修改为0,读写头转向左侧邻格,转入<状态,指令执行4(<,0;1,R,>): 当前状态为<,且当前字符为0,则将当前字符修改为1,读写头转向右侧邻格,转入>状态,指令执行1(<,#;1,R,>): 当前状态为>,且当前字符为0,指令不执行,可省略
(>,0;0,R,>): 当前状态为>,且当前字符为0,则将当前字符修改为0,读写头转向右侧邻格,转入>状态,指令执行4(>,#;#,L,h): 当前状态为>,且当前字符为#,则将当前字符修改为#,读写头转向左侧邻格,转入h状态并停机

RAM running example

Insert picture description here

RAM算法:
0	R[3] <- 1			
1	R[0] <- R[0] + R[3]	// c = 1 + c
2	R[0] <- R[0] - R[1]	// c -= d
3	R[2] <- R[2] + R[3]	// x++
4	IF R[0] > 0 GOTO 2	// c > 0 循环
5	R[0] <- R[2] - R[3]	// else x--
6	STOP				// return x  

c = 1 + c;
for (x = 0; c > 0; x++)
	c -= d;
return x;
Step R[0] R[1] R[2] R[3] Instruction (IR) meaning
0 12 5 0 0 R[3] <- 1
1 ^ ^ ^ 1 R[0] <- R[0] + R[3] c = 1 + c
2 13 ^ ^ ^ R[0] <- R[0] - R[1] c-=d
3 8 ^ ^ ^ R[2] <- R[2] + R[3] x++
4 ^ ^ 1 ^ IF R[0] > 0 GOTO 2 c > 0
5 ^ ^ ^ ^ R[0] <- R[0] - R[1] c-=d
6 3 ^ ^ ^ R[2] <- R[2] + R[3] x++
7 ^ ^ 2 ^ IF R[0] > 0 GOTO 2 c > 0
8 ^ ^ ^ ^ R[0] <- R[0] - R[1]] c-=d
9 0 ^ ^ ^ R[2] <- R[2] + R[3] x++
10 ^ ^ 3 ^ IF R[0] > 0 GOTO 2 c < 0
11 ^ ^ ^ ^ R[2] <- R[2] + R[3] x–
12 2 ^ ^ ^ R[2] <- R[2] + R[3] return x
Published 21 original articles · praised 8 · visits 1495

Guess you like

Origin blog.csdn.net/K_Xin/article/details/105372717