描述:
给出两个整数m和n(1<=m<=n),找出m和n之间所有约数的平方和被开方后为整数的数。如42,42的约数为 1, 2, 3, 6, 7, 14, 21, 42。这些约数的平方为1, 4, 9, 36, 49, 196, 441, 1764。它们的和为2500,正好是50的平方。
例如:
返回一个模仿数组的字符串,第一个数为约数平方和被开方后为整数的数,第二个数为它的约数平方和。
listSquared(1, 250) –> “[[1, 1], [42, 2500], [246, 84100]]”
listSquared(42, 250) –> “[[42, 2500], [246, 84100]]”
MyCode:
using System;
using System.Linq;
public class SumSquaredDivisors
{
public static string listSquared(long m, long n)
{
string retStr = "";
while (m <= n)
{
int sum = 0;
for(int i = 1;i <= m;i++)
{
if(m % i == 0)
{
sum += i * i;
}
}
if (Math.Sqrt(sum) % 1 == 0)
{
retStr += string.Format("[{0}, {1}]", m, sum) + ", ";
}
m++;
}
return retStr.Length > 2 ? string.Format("[{0}]", retStr.Substring(0, retStr.Length - 2)) : "[]";
}
}
CodeWar:
using System;
using System.Collections.Generic;
using System.Linq;
public class SumSquaredDivisors
{
public static string listSquared(long m, long n)
{
List<string> result = new List<string>();
for(int i = (int)m; i <= n; i++)
{
int sum = GetDivisors(i).Select(x => x*x).Sum();
if(IsSquare(sum))
{
result.Add(string.Format("[{0}, {1}]", i, sum));
}
}
return "[" + string.Join(", ", result) + "]";
}
private static bool IsSquare(int num)
{
return Math.Sqrt(num) % 1 == 0;
}
private static List<int> GetDivisors(int num)
{
List<int> divs = new List<int>();
for(int i = 1; i <= num; i++)
{
if(num % i == 0)
divs.Add(i);
}
return divs;
}
}