# 编程之美-程序理解和时间分析

113人阅读 评论(0)

using System;
using System.Collections.Generic;
using System.Text;

namespace FindTheNumber
{
class Program
{
static void Main(string[] args)
{
int [] rg =
{2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
18,19,20,21,22,23,24,25,26,27,28,29,30,31};

for(Int64 i = 1; i < Int64.MaxValue; i++)
{
int hit = 0;
int hit1 = -1;
int hit2 = -1;
for (int j = 0; (j < rg.Length) && (hit <= 2); j++)
{
if((i % rg[j]) != 0)
{
hit++;
if(hit == 1)
{
hit1 = j;
}
else if (hit == 2)
{
hit2 = j;
}
else
break;

}
}

if((hit == 2) && (hit1 + 1 == hit2))
{
Console.WriteLine("found {0}", i);
}

}
}
}
}


1> 这个程序要找的是符合什么条件的数？
2> 这样的数存在么？符合这一条件的最小的数是什么？
3> 在电脑上运行这一程序，你估计要多长时间才能输出第一个结果？时间精确到分钟(电脑配置：单核CPU2.0GHz，内存和硬盘资源充足)

## 我的解答：

• 1> 第一个问题不难，只要认真分析程序，就能看出来程序求的是这样的数，这个数不能被 rg[k]和rg[k+1]整除(0 <= k < n-1)，同时能被其余所有数(即rg[0],…,rg[k-1]和r[k+2],…,r[n-1])整除。
• 2> 该问的入手点是寻找rg[k]和rg[k+1]。

16=2*8, 18 = 2*9, 20 = 4*5, 22 = 2*11, 24 = 3*8, 26 = 2*13, 28 = 4*7, 30 = 2*15。

• 3> 要估算时间，我们先确定一个原子操作（或者说原子过程更合适），这里我们取内层for循环里的整个if语句块，该段程序主要包括一个取模操作和一个判断，如果进入if语句的话，还包括1次加法操作，1~2次判断和一次赋值操作。

JOJ的2042题目也是一个程序理解题目，这个题目非常有意思，给出了下面一段C++源代码，要求计算出最后的输出结果，源代码如下：

#include<cstdio>
int main(void)
{
int x = 987654321, c = 0, d = 1, e = 6;
while(x--){
c += d,
d += e,
e += 6;
}
printf("%d/n", c);
return 0;
}

We can use axioms to calculate programs just like what we do in algebras. Dijkstra is the one who advocates such constructive approach whereby a program is designed together with its correctness proof. In short, one has to start from a given postcondition Q and then look for a program that establishes Q from the precondition. Often, analyzing Q provides interesting hints to finding the program. This approach is quite different from the well known Hoare Logic.

For example, the following program is calculated by Dijkstra's approach. Unfortunately, its annotation is lost so that its function is hard to grasp. You are to help with finding the final value of the variable c. Note that the program is designed under 128-bit architecture.

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：58386次
• 积分：1570
• 等级：
• 排名：千里之外
• 原创：93篇
• 转载：43篇
• 译文：0篇
• 评论：6条
评论排行
最新评论