约数娱乐(1)

描述:

给出两个整数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;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值