描述:
给出两个整数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;
}
}

本文介绍了一个编程挑战:寻找指定范围内所有约数的平方和能构成完全平方数的整数,并提供了解决方案的两种实现方式。通过遍历每个整数,计算其约数的平方和,如果该和为完全平方数,则将该整数及其约数平方和加入结果列表。
410

被折叠的 条评论
为什么被折叠?



