Problem Statement:
leetcode problem 2894. Divisible and Non-divisible Sums Difference -
You are given positive integers n and m.
Define two integers as follows:num1: The sum of all integers in the range [1, n] (both inclusive) that are not divisible by m.
num2: The sum of all integers in the range [1, n] (both inclusive) that are divisible by m.
Return the integer num1 - num2.
Define two integers as follows:num1: The sum of all integers in the range [1, n] (both inclusive) that are not divisible by m.
num2: The sum of all integers in the range [1, n] (both inclusive) that are divisible by m.
Return the integer num1 - num2.
Initial Code
class Solution { public int differenceOfSums(int n, int m) { int suma = 0;sumb=0; // ERROR: sumb not declared properly for (int i=1; i==n; i++){ // ERROR: i==n (this never iterates) if(i%m==0){ sumb+=i; }else{ suma+=i; } } return suma-sumb; } }
Issues in the code:
- Variable declaration:
sumb
is undeclared. - Loop condition:
for (int i = 1; i == n; i++)
executes only wheni
equalsn
, so it never loops. It must bei <= n
. - Minor style: combining declarations on one line makes it harder to read
Corrected code
class Solution { public int differenceOfSums(int n, int m) { int suma = 0; int sumb = 0; for (int i = 1; i <= n; i++) { if (i % m == 0) sumb += i; else suma += i; } return suma - sumb; } }