Accenture Coding Question 1
Coding Question 1
The function def differenceofSum(n. m) accepts two integers n, m as arguments Find the sum of all numbers in range from 1 to m(both inclusive) that are not divisible by n. Return difference between sum of integers not divisible by n with sum of numbers divisible by n.
Assumption:
- n>0 and m>0
- Sum lies between integral range
Example
Input
n:4
m:20
Output
90
Explanation
- Sum of numbers divisible by 4 are 4 + 8 + 12 + 16 + 20 = 60
- Sum of numbers not divisible by 4 are 1 +2 + 3 + 5 + 6 + 7 + 9 + 10 + 11 + 13 + 14 + 15 + 17 + 18 + 19 = 150
- Difference 150 – 60 = 90
Sample Input
n:3
m:10
Sample Output
19
Python
C
C++
Java
Python
Run
n = int(input())
m = int(input())
sum_divisible = 0
sum_not_divisible = 0
for i in range(1, m+1):
if i % n == 0:
sum_divisible += i
else:
sum_not_divisible += i
print(abs(sum_not_divisible - sum_divisible))
C
Run
#includeint differenceOfSum(int n, int m) { int i, sum1 = 0, sum2 = 0; for (i = 1; i <= m; i++) { if (i % n == 0) { sum1 = sum1 + i; } else { sum2 = sum2 + i; } } return sum2 - sum1; } int main() { int n, m; int result; scanf("%d", &n); scanf("%d", &m); result = differenceOfSum(n, m); printf("%d", result); return 0; }
C++
Run
#includ<bits/stdc++.h>
using namespace std;
int differenceofSum(int n, int m)
{
int i, sum1 = 0, sum2 = 0;
for(i=1; i<=m; i++)
{
if(i%n==0)
{
sum1 = sum1 + i;
}
else
{
sum2 = sum2 + i;
}
}
return sum2 - sum1;
}
int main()
{
int n, m;
int result;
cin>>n>>m;
result = differenceofSum(n, m);
cout<<result;
return 0;
}Java
Run
import java.util.*;
class Solution
{
public static int differenceOfSum (int m, int n)
{
int sum1 = 0, sum2 = 0;
for (int i = 1; i <= m; i++)
{
if (i % n == 0)
sum1 = sum1 + i;
else
sum2 = sum2 + i;
}
return Math.abs (sum1 - sum2);
}
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
int m = sc.nextInt ();
System.out.println (differenceOfSum (m, n));
}
}Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
