您的位置:首页 > 其它

韩信点兵问题的简单算法(downmoon)

2009-09-24 10:25 274 查看
有朋友问起这个问题:

爱因斯坦曾出过这样一道有趣的数学题,有一个长阶梯,每步上2阶,最后剩1阶;若每步上3阶,最后剩2阶,若每步上5阶,后剩4阶;若每步上6阶,最后剩5阶;只有每步上7阶,最后一阶也不剩。问至少有多少阶阶梯?编写一个JAVA程序,解决该问题。

这个是我国古代的韩信点兵问题:古人用剩余定理口算或心算,我们现在有计算机了,算法很简单:

我以C#为例,Java非常类似。JAVA

view plaincopy to clipboardprint?

public static void main(String[] args) {
int x;
for (x = 0; x < 200; x++)
{
if (x % 2 == 1 && x % 3 == 2 && x % 5 == 4 && x % 6 == 5 && x % 7 == 0)
{
System.out.print("这个数字是:" +x);
}
}
}

public static void main(String[] args) {
int x;
for (x = 0; x < 200; x++)
{
if (x % 2 == 1 && x % 3 == 2 && x % 5 == 4 && x % 6 == 5 && x % 7 == 0)
{
System.out.print("这个数字是:" +x);
}
}
}


说明:因为要取最小数,所以先设最大值100,无解,再设为200,得119

C#:

view plain
copy to clipboard
print
?

static
void Main( string [] args)

{
int x;

for (x = 0; x < 200; x++)

{
if (x % 2 == 1 && x % 3 == 2 && x % 5 == 4 && x % 6 == 5 && x % 7 == 0)

{
Console.WriteLine("这个数字是:"
+ x.ToString());
}
}
Console.ReadKey();
}

static void Main(string[] args)
{
int x;
for (x = 0; x < 200; x++)
{
if (x % 2 == 1 && x % 3 == 2 && x % 5 == 4 && x % 6 == 5 && x % 7 == 0)
{
Console.WriteLine("这个数字是:" + x.ToString());
}
}
Console.ReadKey();
}


后来有朋友提起是7的倍数,

于是再优化下:

view plain
copy to clipboard
print
?

static
void Main( string [] args)

{
int x;

for (x = 0; x < 200; x = x + 7)

{
if (x % 2 == 1 && x % 3 == 2 && x % 5 == 4 && x % 6 == 5)

{
Console.WriteLine("这个数字是:"
+ x.ToString());
}
}
Console.ReadKey();
}

static void Main(string[] args)
{
int x;
for (x = 0; x < 200; x = x + 7)
{
if (x % 2 == 1 && x % 3 == 2 && x % 5 == 4 && x % 6 == 5)
{
Console.WriteLine("这个数字是:" + x.ToString());
}
}
Console.ReadKey();
}


再考虑是奇数,更加简洁:

view plain
copy to clipboard
print
?

static
void Main( string [] args)

{
int x;

for (x = 7; x < 200; x = x + 14)

{
if ( x % 3 == 2 && x % 5 == 4 && x % 6 == 5)

{
Console.WriteLine("这个数字是:"
+ x.ToString());
}
}
Console.ReadKey();
}

static void Main(string[] args)
{
int x;
for (x = 7; x < 200; x = x + 14)
{
if ( x % 3 == 2 && x % 5 == 4 && x % 6 == 5)
{
Console.WriteLine("这个数字是:" + x.ToString());
}
}
Console.ReadKey();
}


再考虑:台阶阶梯总数加一是为2、3、5、6的最小公倍数,而且是7的倍数,所以定是30的倍数减1,可得如下算法:

view plain
copy to clipboard
print
?

static
void Main( string [] args)

{
int x;

for (
int i = 1; i < 10; i++)
{
if ((i * 30 - 1) % 7 == 0)

{
x = (i * 30 - 1);
Console.WriteLine("这个数字是:"
+ x.ToString());
}
}
Console.ReadKey();
}

static void Main(string[] args)
{
int x;
for (int i = 1; i < 10; i++)
{
if ((i * 30 - 1) % 7 == 0)
{
x = (i * 30 - 1);
Console.WriteLine("这个数字是:" + x.ToString());
}
}
Console.ReadKey();
}


助人生于自助。3w@live.cn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: