0% found this document useful (0 votes)
2 views13 pages

Module 5 Solutions

The document outlines several programming tasks including perfect number detection, calculating unique product sales, efficient budget allocation, character swapping in strings, updating matrix values for weather forecasts, calculating water tank filling time, and finding divisible sub-numbers in transaction IDs. Each task includes a description, function signature, input/output format, and example. The solutions provided are in C++ and demonstrate how to implement the required functionalities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Module 5 Solutions

The document outlines several programming tasks including perfect number detection, calculating unique product sales, efficient budget allocation, character swapping in strings, updating matrix values for weather forecasts, calculating water tank filling time, and finding divisible sub-numbers in transaction IDs. Each task includes a description, function signature, input/output format, and example. The solutions provided are in C++ and demonstrate how to implement the required functionalities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Perfect Number Detection for Vault Security:

In a high-security vault, the system checks the integrity of access codes to ensure they are "perfect"
codes. A "perfect" code is a special access code where the sum of its proper divisors (excluding the
code itself) equals the code number. If the code is perfect, the system grants access; otherwise, it
returns the sum of its proper divisors to indicate the code's validity. Your task is to write a program that
determines if a given code is perfect or returns the sum of its proper [Link] a function that
accepts an integer n representing the access code and:

 Returns 1 if the number is a perfect number.


 Otherwise, returns the sum of the proper divisors of the number.
Function Signature

int detectPerfectNumber(int n)

Input Format

 The input consists of a single integer n.


Output Format

 The output is either 1 (if n is a perfect number) or the sum of the proper divisors of n.

Example 1

Sample Input 1

22

Sample Output 1

14

Explanation

The proper divisors of 22 are 1, 2, and 11. The sum of these divisors is 14, which is not equal to 22.
Hence, the code is not perfect, and the sum of proper divisors 14 is returned.

Solution:

#include<iostream>

using namespace std;

int perfect(int n){

int sum=0;

for(int i=1;i<n;i++){

if(n%i==0){

sum+=i;

}
return sum;

int main(){

int n;

cin>>n;

int res=perfect(n);

if(n==res){

cout<<1;

}else{

cout<<res;

2. Calculating the Total of Unique Products Sold:

You are working as an inventory manager for an e-commerce company. The company tracks the
products sold across different regions. However, some products might be sold in multiple regions, and
they want to calculate the total sales of products that have only been sold in one region. This means
you need to find the sum of product IDs that appear only once in the list.

You are given an array of product IDs, where each product ID represents a product sold. Your task is to
write a program that calculates the sum of unique product IDs, i.e., those that appear exactly once in
the array. If no product ID is unique (i.e., all appear more than once), return 0.

Function Signature

int SumUniqueElements(int[] arr, int length);

Assumptions

 The length of the array is always greater than 0.


 The product IDs in the array are positive integers.
 You need to sum only those product IDs which appear exactly once.
Input Format

 The first input is the size of the array, length.


 The second input is the array arr which contains the product IDs.
Constraints

 1 ≤ length ≤ 10000
 The product IDs in the array are positive integers within the integer range.
Output Format

 You need to output the sum of all unique product IDs.


Example 1

Sample Input 1

8
25479248

Sample Output 1

29

Explanation

 The product IDs 2 and 4 appear more than once, so they are not included in the sum.
 The unique product IDs are 5, 7, 9, and 8. Their sum is 29.
Solution:

#include <iostream>

using namespace std;

int uniquesum(int arr[], int n) {

int sum = 0;

for (int i = 0; i < n; i++) {

int count = 0;

for (int j = 0; j < n; j++) {

if (arr[i] == arr[j]) {

count++;

if (count == 1) {

sum += arr[i];

return sum;

int main() {

int n;

cin >> n;

int arr[n];

for (int i = 0; i < n; i++) {

cin >> arr[i];

}
cout << uniquesum(arr, n) << endl;

return 0;

Postclass:

1. Efficient Budget Allocation for Project Expenses:

Imagine you are working in a project management company responsible for handling budgets for
various projects. Each project involves allocating funds to either odd-numbered or even-numbered
categories. For instance, categories numbered with an even digit might represent equipment expenses,
while odd-digit categories represent employee wages. The goal is to maximize the efficiency of your
budget by allocating it to the category (either odd or even) that has a greater total sum.

Your task is to implement a function that calculates the sum of all odd-digit expenses and the sum of all
even-digit expenses from a given project budget number. The program should then output the higher
sum to aid in efficient budget allocation.

Function Description

int OddEvenSum(int num)

The function OddEvenSum accepts a non-negative integer num representing the project budget. The
function should find the sum of all odd digits and the sum of all even digits in num and return the
greater sum. If both sums are equal, return either one.

Input Format

 A single integer num representing the project budget.

Output Format

 An integer representing the greater sum between the sum of odd digits and the sum of even digits.

Example 1

Sample Input 1

98631

Sample Output 1

14

Explanation

 Sum of odd digits: 9 + 3 + 1 = 13


 Sum of even digits: 8 + 6 = 14
 Since the sum of even digits is greater, the output is 14.

Solution:

#include<iostream>

using namespace std;

int oddevensum(int n){


int esum=0,osum=0;

while(n!=0)

int r=n%10;

if(r%2==0)

esum+=r;

}else{

osum+=r;

n=n/10;

if(esum>osum){

return esum;

}else{

return osum;

int main(){

int n;

cin>>n;

int res=oddevensum(n);

cout<<res;

[Link] Letters in a Text

You are given a string representing a name of a product, and you need to perform a modification based
on customer feedback. Some customers have complained that two characters in the product name are
often confusing and they want the characters swapped. You are tasked with writing a function that
swaps two characters in the product name wherever they occur.

Function Description:

String replaceCharacter(String str, int n, char ch1, char ch2)

 The function accepts three arguments:


 str[]: A string str of length n containing only lowercase alphabets.
 n: The length of the string str[].
 ch1: The character to be replaced by ch2.
 ch2: The character to be replaced by ch1.
 The function modifies the string in place by swapping every occurrence of ch1 with ch2 and vice versa.
Note

 If the string is empty, return null (None, in case of Python).


 If both characters ch1 and ch2 do not exist in the string or are the same, return the original string
unchanged.
Input Format

 A string str[] of lowercase alphabetical letters.


 Two characters ch1 and ch2.
Output Format

 The modified string with ch1 and ch2 swapped wherever they occur.
Example 1

Sample Input 1

apples

Sample Output 1

paales

Explanation

In the string "apples", every occurrence of 'a' is replaced with 'p', and every occurrence of 'p' is replaced
with 'a', resulting in "paales".

Solution:

#include <iostream>

#include <string>

using namespace std;

string replaceCharacter(string str, char ch1, char ch2) {

if ([Link]()==0)

return "";

for (size_t i = 0; i < [Link](); ++i) {

if (str[i] == ch1)

str[i] = ch2;

else if (str[i] == ch2)

str[i] = ch1;

return str;
}

int main() {

string s;

getline(cin,s);

char a, b;

cin >> a >> b;

cout << replaceCharacter(s, a, b);

return 0;

[Link] Update for Weather Forecast Analysis:

Imagine you're working for a weather forecasting company that monitors the temperature across
different regions. They use a matrix to represent the temperature readings of various cities in a square
grid (with rows and columns representing different cities). The system wants to update the temperature
values on the diagonal (cities where the row number equals the column number) by calculating the sum
of the surrounding cities' temperatures. This helps to smooth out any extreme temperature fluctuations
along the diagonal that might be outliers. Your task is to write a function to modify the diagonal
temperatures based on the sum of the surrounding temperatures.

Problem Statement

You are given an m x m matrix where each element represents the temperature in a specific city. The
matrix has m rows and m columns. You need to replace the temperature of the diagonal elements
(where the row number i equals the column number j) with the sum of the surrounding elements. The
surrounding elements of a diagonal element include:

 Top, Bottom, Left, Right


 Diagonal elements (top-left, top-right, bottom-left, bottom-right)
Function Description

public static int[][] ReplaceDiagonal(int[][] mat, int m)

The updated matrix should be returned, and if the matrix is empty, return the matrix unchanged.

Input Format

 The first line contains an integer m, the size of the matrix.


 The next m lines contain m integers, representing the matrix.

Constraints

 m is an integer such that 1 <= m <= 1000.


 The matrix is m x m, and each element is an integer within the range of standard integer limits.

Output Format

 Output the matrix with updated diagonal elements.


Example 1

Sample Input 1

123

456

789

Sample Output 1

11 2 3

4 50 6

7 8 64

Explanation

The diagonal elements are: 1, 5, 9

- For 1, the surrounding elements are: 2, 4, 5 → Sum = 11

- For 5, the surrounding elements are: 11, 2, 3, 4, 6, 7, 8, 9 → Sum = 50

- For 9, the surrounding elements are: 50, 6, 8 → Sum = 64

Solution:

#include <iostream>

#include <algorithm>

using namespace std;

const int MAX = 100;

void func(int n, int arr[][MAX]) {

for (int i = 0; i < n; i++) {

int sum = 0;

int rs = max(0, i - 1);

int re = min(n - 1, i + 1);

int cs = max(0, i - 1);


int ce = min(n - 1, i + 1);

for (int j = rs; j <= re; j++) {

for (int k = cs; k <= ce; k++) {

if (j != i || k != i) {

sum += arr[j][k];

arr[i][i] = sum;

int main() {

int n;

cin >> n;

int arr[MAX][MAX];

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

cin >> arr[i][j];

func(n, arr);

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

cout << arr[i][j];

if(j != n-1)

cout << " ";


}

cout << "\n";

return 0;

[Link] Tank Filling Time Calculation


You are a project manager at a construction site, tasked with designing the plumbing system for a new
water reservoir. The rectangular tank needs to be filled using a high-efficiency pump with a known
filling rate. You need to calculate how much time it will take to completely fill the water tank. The
tank’s dimensions (length, breadth, and height) and the pump's filling rate are provided, and you are
expected to compute the time required to fill the tank.

You are given the dimensions of a rectangular tank (length, breadth, and height) and the rate at which a
pump fills the tank. You need to calculate the time required to fill the tank using the formula:

 Time required = Volume of the rectangular tank / Rate at which the pipe fills the tank
Where:

 Volume of the rectangular tank = Length × Breadth × Height


 Rate at which pipe fills the tank is given as an integer.
You need to implement the function to return the computed time in integer form (ignoring fractional
time values).

Function Signature

int TimeToFill(int l, int b, int h, int r);

Input Format

 l (1 ≤ l ≤ 1000) — Length of the rectangular tank.


 b (1 ≤ b ≤ 1000) — Breadth of the rectangular tank.
 h (1 ≤ h ≤ 1000) — Height of the rectangular tank.
 r (1 ≤ r ≤ 1000) — Rate at which the pipe fills the tank.

Output Format

 Returns the time required (in integer form) to fill the rectangular tank.

Example 1

Sample Input 1

20

50

70

350
Sample Output 1

200

Explanation

 Volume of the rectangular tank = Length × Breadth × Height = 20 × 50 × 70 = 70000 cubic units
 Time required = Volume of the rectangular tank / Rate = 70000 / 350 = 200 Thus, the time required to
fill the tank is 200 units.

Solution:

#include <iostream>

using namespace std;

int vol(int l, int b, int h) {

return l * b * h;

int timeRequired(int a, int rate) {

return a / rate;

int main() {

int l, b, h, rate;

cin >> l >> b >> h >> rate;

int a = vol(l, b, h);

cout << timeRequired(a, rate) << endl;

return 0;

[Link] Divisible Sub-Numbers in a Transaction ID

Imagine you work in a transaction processing system where each transaction is identified by a unique
ID number. These transaction IDs are often used in audit processes to find patterns or checks,
especially when verifying divisibility by certain values, such as 11. You are tasked with identifying all
contiguous sub-transaction IDs (fragments) within a given transaction ID that are divisible by 11.
These sub-transaction IDs represent various combinations of digits that could correspond to different
parts of a larger transaction.
Your task is to implement a function that returns the count of contiguous integer fragments of a
transaction ID that are divisible by 11. Each fragment is formed by considering consecutive digits in
the transaction ID.

You are given an integer num, which represents a transaction ID. You need to count how many
contiguous integer fragments of num are divisible by 11.

Function Signature

int divisibilityByEleven(int num);

Input Format

 A positive integer num representing a transaction ID (1 ≤ num ≤ 109).

Output Format

 Returns the number of contiguous integer fragments of num that are divisible by 11.

Example 1

Sample Input 1

1215598

Sample Output 1

Explanation

 The fragments divisible by 11 are:


 55, 121, 12155, 15598 Thus, there are 4 such fragments.

Solution:

#include <iostream>

#include <string>

using namespace std;

int divisibilityByEleven(long long num) {

string s = to_string(num);

int count = 0;

int n = [Link]();
for (int i = 0; i < n; i++) {

for (int j = i + 1; j <= n; j++) {

string fragment = [Link](i, j - i);

long long value = stoll(fragment);

if (value % 11 == 0) {

count++;

return count;

int main() {

long long num;

cin >> num;

int result = divisibilityByEleven(num);

cout << result << endl;

return 0;

You might also like