返回介绍

solution / 2700-2799 / 2778.Sum of Squares of Special Elements / README_EN

发布于 2024-06-17 01:03:00 字数 3281 浏览 0 评论 0 收藏 0

2778. Sum of Squares of Special Elements

中文文档

Description

You are given a 1-indexed integer array nums of length n.

An element nums[i] of nums is called special if i divides n, i.e. n % i == 0.

Return _the sum of the squares of all special elements of _nums.

 

Example 1:

Input: nums = [1,2,3,4]
Output: 21
Explanation: There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. 
Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21.  

Example 2:

Input: nums = [2,7,1,19,18,3]
Output: 63
Explanation: There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. 
Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. 

 

Constraints:

  • 1 <= nums.length == n <= 50
  • 1 <= nums[i] <= 50

Solutions

Solution 1

class Solution:
  def sumOfSquares(self, nums: List[int]) -> int:
    n = len(nums)
    return sum(x * x for i, x in enumerate(nums, 1) if n % i == 0)
class Solution {
  public int sumOfSquares(int[] nums) {
    int n = nums.length;
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
      if (n % i == 0) {
        ans += nums[i - 1] * nums[i - 1];
      }
    }
    return ans;
  }
}
class Solution {
public:
  int sumOfSquares(vector<int>& nums) {
    int n = nums.size();
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
      if (n % i == 0) {
        ans += nums[i - 1] * nums[i - 1];
      }
    }
    return ans;
  }
};
func sumOfSquares(nums []int) (ans int) {
  n := len(nums)
  for i, x := range nums {
    if n%(i+1) == 0 {
      ans += x * x
    }
  }
  return
}
function sumOfSquares(nums: number[]): number {
  const n = nums.length;
  let ans = 0;
  for (let i = 0; i < n; ++i) {
    if (n % (i + 1) === 0) {
      ans += nums[i] * nums[i];
    }
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文