Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
static void p_21()
{
ArrayList ans = new ArrayList();
for (int n = 2; n <= 10000; ++n)
{
int suma = 0;
int sumb = 0;
int[] a = solutions.factor(n);
foreach (int i in a)
{
suma += i;
}
suma -= n;
if (suma != n)
{
a = solutions.factor(suma);
foreach (int i in a)
{
sumb += i;
}
sumb -= suma;
if (n == sumb)
{
if (ans.Count == 0)
{
ans.Add(n);
ans.Add(suma);
}
else
{
bool isoktoadd = true;
foreach (int i in ans)
{
if (sumb == i)
{
isoktoadd = false;
break;
}
}
if (isoktoadd)
{
ans.Add(n);
ans.Add(suma);
}
}
}
}
}
int sum = 0;
foreach (int i in ans)
{
Console.WriteLine(i.ToString());
sum += i;
}
Console.WriteLine("ans:{0}", sum);
}
再利用できるように因数分解関数を作った
/// <summary>
/// 因数分解
/// </summary>
/// <param name="n">因数分解する数</param>
/// <returns>異常なら1、正常なら因数分解されたint型配列を返す</returns>
public static int[] factor(int n)
{
if (n <= 1)
{
int[] res = new int[1];
res[0] = 1;
return res;
}
else
{
ArrayList factors = new ArrayList();
int f = 2;
factors.Add(1);
while (n >= f)
{
if ((int)(n / f) * f == n)
{
factors.Add(f);
}
++f;
}
int[] res = (int[])factors.ToArray(typeof(int));
return res;
}
}
0 件のコメント:
コメントを投稿