Description
Sum of Squares of Special Elements
EasyYou 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 <= 501 <= nums[i] <= 50
Solutions
This function adds up the squares of the numbers sitting at special positions in the array, where a position is special if its 1-based index divides the array length evenly. It stores the length in n, starts a running total res at 0, and loops over every index i. Because JavaScript arrays are 0-based, the 1-based position is i + 1, so the check n % (i + 1) === 0 asks whether that position is a divisor of n. When it is, the element is multiplied by itself and added to res. After the loop finishes, res holds the sum of the squares of all elements at divisor positions and is returned.
/**
* @param {number[]} nums
* @return {number}
*/
var sumOfSquares = function(nums) {
const n = nums.length;
let res = 0;
for (let i = 0; i < n; i++) {
if (n % (i + 1) === 0) {
res += nums[i] * nums[i];
}
}
return res;
};