Sunday, November 1, 2015

Funny C Program:Zhishen Lu Eating Steamed Bun v1

Zhishen Lu,who is called "flower monk",is one of the 108 heroes in All Men Are Brothers,which is one of the Four Great Classical Novels of Chinese literature.It's said that he went to the daxiangguo temple in Prefecture of Kaifeng at a noon in a hurry to bum lunch.But there were only 99 steamed buns for 99 monks in the temple exactly.So what happened later?
The elder Zhiqing didn't want to offend Zhishen Lu,so he figured out a good idea.
Firstly,he arranged Zhishen Lu at a specific position.
Then,the elder said to all the people,"let's form a ring to number off beginning from me.The 5th men can get a steamed bun and leave."Other people continued to number off from 1 to 5,of course.
Finally,all men but Zhishen Lu ate a steamed bun.What a surprise!
Here comes the problem,"how did it happen?Or,where are Zhishen Lu?"
Smart friends,can you find the position number of Zhishen Lu?
As a matter of fact,I knew this story from a mooc teaching C programming.And I was prompted to use sieve method.Although prompted,I spent one day to find the correct answer.Too long,right?What's worse,I still have some doubts after knowing the answer.It appeared terrible,however,I learned a lot.
Now share my first version of the source code.

//Zhishen Lu Eating Steamed Bun v1
#include <stdio.h>
int main(void)
{
int monk[101]={0},count=0,steabun=0,i=0;//Easy to count.monk[1]~monk[100] for the flower monk Zhishen Lu and other 99 monks,value 0 means they will participate in numbering off.count to number off,steabun for the number of steamed buns already divided and i as a simple counter.
while (steabun<99&&!monk[++i])
{
if (++count%5==0)
{
monk[i]=1;//Get a steamed bun
steabun++;
}
if (i==100)
i=0;//Next circle
}
for(i=1;monk[i];i++) ;//Do you know why ";" exists?
printf("The position number of Zhishen Lu is %d.\n",i);
return 0;
}

Through looking at it,do you find any problems.If not,debug or run it in person.
As a matter of fact,when I finnished this code,I was ecstatic,with great achievability of solving this problem.But quickly,I felt disappointed looking at the result printed on the screen,"The position number of Zhishen Lu is 1. "
Of course,it's wrong,for the elder was at the 1st position.How to correct?I was frustrated.Want to know more?Follow my posts next several days.
In addition,I wrote,compile,and run the code on C4droid on my Android phone,and my blogs are posted through the mobile phone,too.As the operations on the Android phone are limited,such as no debugger on it,so you can barely see pictures in my blogs,and the code was not highlighted.I'm sorry and embarrassed for my economic condition not to buy a computer.But I'm still glad to share.I hope you can gain something through reading my blogs.Thanks.