一只兔子躲进了 10 个环形分布的洞的某一个,狼在第一个洞没有找到兔子,就隔一个洞,到第三个洞去找,也没有找到,就隔两个洞,到第六个洞去找,以后每次多隔一个洞 去找兔子……这样下去,结果一直找不到兔子,请问:兔子可能躲在哪个洞中?
算法思想:
第几次 | 洞口编号 |
---|---|
(1) | 1 |
(2) | (1)+2=3 |
(3) | (2)+3=6 |
(4) | (3)+4=10 |
(5) | (4)+5=10+5 |
(6) | (5)+6=2*10+1 |
(7) | (6)+7=2*10+8 |
(8) | (7)+8=3*10+6 |
(9) | (8)+9=4*10+5 |
(10) | (9)+10=5*10+5 |
C#代码实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace 狼追兔子问题
{
class Program
{
static void Main(string[] args)
{
int x1 = 1;
int x2 = 0;
int yushu; //狼可以去的洞口
int[] a = new int[] {0,1,2,3,4,5,6,7,8,9,10};
for (int i = 2; i < 100; i++)
{
if (x1 % 10 == 0)
{
yushu = x1 % 10 + 10; //第10个洞口
}
else
{
yushu = x1 % 10 ;
}
//Console.Write(yushu + " ");
for (int j = 0; j < a.Length; j++)
{
if (yushu == j)
{
a[j] = 0; //经过的洞口号码在数组中置0
}
}
x2 = x1 + i;
x1 = x2;
}
Console.WriteLine("兔子可能躲的洞是:");
for (int i = 0; i < a.Length; i++) //数组用a.Length的方法来界定长度,最不容易数组越界
{
if (a[i] != 0) //去掉数组中已经置0的成员
{
Console.Write(a[i] + " ");
}
}
Console.ReadKey();
}
}
}
输出的结果是:
兔子可能躲的洞是:
2 4 7 9