1 雷卡曼数(Recamán Number)
雷卡曼数(Recamán Number),即Recaman序列被定义如下:
(1) a[0]=0;
(2) 如果a[m-1]-m>0并且这个值在序列中不存在,则a[m]=a[m-1]-m;
(3) 否则a[m]=a[m-1]+m;
雷卡曼序列的前几个数的数值是:0,1,3,6,2,7,13,20,12,21,11,22,10,23,9,,,,
2 源程序
using System;
using System.Collections;
using System.Collections.Generic;
namespace Legalsoft.Truffer.Algorithm
{
public static partial class Number_Sequence
{
public static int Recaman_Number(int n)
{
int[] arr = new int[n];
arr[0] = 0;
for (int i = 1; i < n; i++)
{
int curr = arr[i - 1] - i;
for (int j = 0; j < i; j++)
{
if ((arr[j] == curr) || curr < 0)
{
curr = arr[i - 1] + i;
break;
}
}
arr[i] = curr;
}
return arr[n - 1];
}
public static int Recaman_Number_Second(int n)
{
if (n <= 0)
{
return 0;
}
HashSet<int> s = new HashSet<int>();
s.Add(0);
int prev = 0;
for (int i = 1; i < n; i++)
{
int curr = (prev - i);
if (curr < 0 || s.Contains(curr))
{
curr = (prev + i);
}
s.Add(curr);
prev = curr;
}
return prev;
}
}
}
POWER BY TRUFFER.CN 50018.COM
3 代码格式
cs
using System;
using System.Collections;
using System.Collections.Generic;
namespace Legalsoft.Truffer.Algorithm
{
public static partial class Number_Sequence
{
public static int Recaman_Number(int n)
{
int[] arr = new int[n];
arr[0] = 0;
for (int i = 1; i < n; i++)
{
int curr = arr[i - 1] - i;
for (int j = 0; j < i; j++)
{
if ((arr[j] == curr) || curr < 0)
{
curr = arr[i - 1] + i;
break;
}
}
arr[i] = curr;
}
return arr[n - 1];
}
public static int Recaman_Number_Second(int n)
{
if (n <= 0)
{
return 0;
}
HashSet<int> s = new HashSet<int>();
s.Add(0);
int prev = 0;
for (int i = 1; i < n; i++)
{
int curr = (prev - i);
if (curr < 0 || s.Contains(curr))
{
curr = (prev + i);
}
s.Add(curr);
prev = curr;
}
return prev;
}
}
}