Sum of digits in C++ - c++

program asked is sum of digits :
Input data are in the following format:
first line contains N - the number of values to process;
and then N lines will follow describing the values for which sum of digits should be calculated by 3 integers A B C;
for each case you need to multiply A by B and add C (i.e. A * B + C) - then calculate sum of digits of the result.
Answer should have N results, also separated by spaces
MY CODE IN C++ :
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
while (t % 10 != 0)
{
sum = sum + t % 10;
t = t / 10;
}
while (t % 10 == 0)
{
sum = sum;
t = t / 10;
}
}
cout << " ";
cout << sum;
cout << " ";
return 0;
}
I'm having hard time correcting my code.
Any help is appreciated.
My assumption is there should be a better way to code this other than using 2 while loops.
PS : I checked other topics just want somebody that could help with my code thank you.

You don't need second while loop, and first one should be corrected to while (t != 0). After that your program for computing sum works correctly.
Try it online!
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
while (t != 0)
{
sum = sum + t % 10;
t = t / 10;
}
}
cout << " ";
cout << sum;
cout << " ";
return 0;
}
Input:
1
123 456 789
Output:
33
Just noticed that you need N separate outputs instead of single sum (like you did), so then your program becomes like this:
Try it online!
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
sum = 0;
while (t != 0)
{
sum = sum + t % 10;
t = t / 10;
}
cout << sum << " ";
}
return 0;
}
Input:
2
123 456 789
321 654 987
Output:
33 15

Related

Why my empty string assignment doesn't clear my string

I have an exercise which looks like that:
Problem statement is simple and straight forward . You will be given a non-negative integer P of length N and you need to check whether
it's divisible by Q ?
Integer P will be given in its decimal representation with P0 as leftmost digit and P1 as second digit from left !
Rest of the digit can be generated from the formula :
Pi = ( 4*Pi-1 + Pi-2 ) modulo Q for 2 <= i <= N-1
Input
The first line contains one integer T - denoting the number of test cases.
T lines follow each containing four integers P0 , P1 , Q and N !
Output
For each testcase output YES if the corresponding integer is divisible by Q and NO otherwise.
Constraints
T <= 100000
0 < P0 , P1 , Q < 10
0 < N <= 1018
Example
Input:
4
1 4 2 2
1 4 2 1
4 2 3 2
3 4 7 3
Output:
YES
NO
YES
NO
Explanation
Value of P is 14, 1, 42, 345 in respective cases !
and that's what I came up with
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int t, q, n, p_0, p_1, p_temp, p;
vector<int> digits;
vector<string> answers;
string number = "";
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> p_0 >> p_1 >> q >> n;
if (n == 1)
{
digits.push_back(p_0);
}
else
{
digits.push_back(p_0);
digits.push_back(p_1);
for (int i = 2; i <= (n - 1); i++)
{
p_temp = (4 * digits[i - 1] + digits[i - 2]) % q;
digits.push_back(p_temp);
}
}
for (int i = 0; i < digits.size(); i++)
{
number += to_string(digits[i]);
}
p = stoi(number);
cout << number << endl;
if (p % q == 0)
{
answers.push_back("YES");
}
else
{
answers.push_back("NO");
}
number = "";
}
for (int i = 0; i < answers.size(); i++)
{
cout << answers[i] << endl;
}
}
Everything I have done works fine, except for one thing, this part does not clear my number variable
number = "";
And honestly I don't know why, could someone correct my mistakes and explain me what did I do wrong. Thanks.
Your problem is with the digits vector.
Each loop the number string just gets repopulated with the digits vector which is never cleared.
Use digits.clear() to empty the vector like so:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int t, q, n, p_0, p_1, p_temp, p;
vector<int> digits;
vector<string> answers;
string number = "";
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> p_0 >> p_1 >> q >> n;
if (n == 1)
{
digits.push_back(p_0);
}
else
{
digits.push_back(p_0);
digits.push_back(p_1);
for (int i = 2; i <= (n - 1); i++)
{
p_temp = (4 * digits[i - 1] + digits[i - 2]) % q;
digits.push_back(p_temp);
}
}
for (int i = 0; i < digits.size(); i++)
{
number += to_string(digits[i]);
}
p = stoi(number);
cout << number << endl;
if (p % q == 0)
{
answers.push_back("YES");
}
else
{
answers.push_back("NO");
}
digits.clear();
number = "";
}
for (int i = 0; i < answers.size(); i++)
{
cout << answers[i] << endl;
}
}
To clear a string you can/should use std::string::clear() as:
number.clear();
There may be other logical errors in your program which may be the reason for not getting the output you expect.
Also instead of creating/initializing the string number using string number = "";, you should use
string number;//no need to write = ""

Fastest way to sum 3 numbers digits

I have been asked by my teacher to solve this problem: "You get 3 different numbers as input, of different length, you have to determine the sum of the digits of all 3 numbers and also the product"
I solved it like this:
#include <bits/stdc++.h>
using namespace std;
int main () {
int a, b, c, S, P;
cin >> a >> b >> c;
S = 0;
P = 1;
while (a != 0) {
int c1 = a % 10;
S += c1;
P *= c1;
a /= 10;
}
while (b != 0) {
int c1 = b % 10;
S += c1;
P *= c1;
b /= 10;
}
while (c != 0) {
int c1 = c % 10;
S += c1;
P *= c1;
c /= 10;
}
cout << S << ' ' << P << endl;
}
My question is, is there a way to solve this more efficient?
You should bother not about the fastest way that does not make sense for such a simple program but about the correctness of the code and avoiding its duplication.
Your program is just incorrect.
For starters the user can interrupt the input. In this case at least one of the variables a, b, c will have indeterminate value. As a result the program will have undefined behavior.
Secondly, as you are using the signed int type when the user can enter negative numbers. In this case you will get an incorrect result because for example sum of digits can occur to be negative.
Thirdly, the user can enter 0 as a value of a number. In this case this number will be skipped in a while loop like this
while (a != 0) {
In this case you again will get an incorrect result because the product of digits can be not equal to zero though it must be equal to zero in this case.
The same while loops are duplicated. That is the program has a redundant code.
The program can be written the following way as it is shown in the demonstrative program below.
#include <iostream>
int main()
{
long long int a = 0, b = 0, c = 0;
std::cin >> a >>b >> c;
long long int sum = 0;
long long int product = 1;
for ( int num : { a, b, c } )
{
const long long int Base = 10;
do
{
long long int digit = num % Base;
if ( digit < 0 ) digit = -digit;
sum += digit;
if ( product ) product *= digit;
} while ( num /= Base );
}
std::cout << "sum = " << sum << '\n';
std::cout << "product = " << product << '\n';
return 0;
}
Move the repeated code to a separate function.
#include <iostream>
using namespace std;
void calc(int num, int &sum, int &product) {
do {
int c1 = num % 10;
sum += c1;
product *= c1;
num /= 10;
}
while (num != 0);
}
int main () {
int a, b, c, S = 0, P = 1;
if (cin >> a >> b >> c) {
calc(a, S, P);
calc(b, S, P);
calc(c, S, P);
cout << S << ' ' << P << endl;
}
return 0;
}

C++: implementing Modular Exponentiation

I am using this New and improved code I corrected in order to solve this question I have.
I am using modular Exponentiation to use the formula [a^k mod n] to get my answer for an assignment I had to do where I was required to code it in two steps.
First int k must be converted to a binary
representation K consisting of a list of 0s and 1s. Second, Modular Exponentiation must be performed
using a, n and K[] as arguments..
Earlier My code was incorrect and was able to correct it.
The Problem I now face is that when I google the online calculator for modular Exponentiation of 5^3 % 13, it should == 8
The result that I get from my code is 5.
I am trying to understand if there something minor I'm missing from the code or my math is wrong? Thanks
#include <iostream>
#include <vector>
using namespace std;
vector <int> BinaryK(int k);
int ModularExpo(int a, vector <int> & k, int n);
int main()
{
int a = 0;
int k = 0;
int n = 0;
cout << "a^k % n" << endl;
cout << "a = ";
cin >> a;
cout << "k = ";
cin >> k;
cout << "n = ";
cin >> n;
vector<int> B = BinaryK(k);
int result = ModularExpo(a, B, n);
cout << "a ^ k mod n == " << result << endl;
return 0;
}
// c == b^e % m
vector<int> BinaryK(int k)
{
vector<int> K; //hint: make K a vector
int tmp = k;
while (tmp > 0)
{
K.push_back(tmp % 2); //hint: use pushback
tmp = tmp / 2;
}
return K;
}
int ModularExpo(int a, vector<int> & K, int n)
{
if (n == 1)
return 0;
int b = 1;
if (K.size() == 0)
return b;
int A = a;
if (K[0] == 1)
b = a;
for (int i = 1; i < K.size() - 1; i++)
{
A = A * A % n;
if (K[i] == 1)
b = A*b % n;
}
return (b);
}
Change this one line:
for (int i = 1; i < K.size(); i++) // K.size() not K.size()-1

How to print common multiples of two number?

I'm trying to print all common multiples of two integers smaller than a certain limit(100 in my case). However, when I call my function, it does nothing. This is my code:
void com_mul(int a, int b)
{
int original = b;
for(int i = 1; a <= 100; i++)
{
a *= i;
b = original;
for(int j = 1; b <= a; j++)
{
b *= j;
if(a == b)
cout << b << ", ";
}
}
}
You can solve this problem much simpler, using a single loop.
In a for loop iterate over potential divisors d from 1 to 100. If d divides both a and b, print d.
You can tell if a number divides another number by applying the % operator, and checking the result for zero:
if (a%d == 0 && b%d == 0) {
cout << d << endl;
}
Tested with a = 4, b = 2, max = 100 on my machine. And it outputs 4.
This is because of the line for (int j = 1; b <= a; j++). j can only go upto 'a'
I think this would do.
#include <iostream>
#include <string>
int main()
{
int a, b, max;
std::cin >> a >> b >> max;
for (int i = a; i <= max; i++)
{
if (i%a == 0 && i%b == 0)
std::cout << i << std::endl;
}
return 0;
}

Find digital roots of a number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is an ACM problem in order to finding the roots of an integer number.
Here is the problem text: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=115
This is my code, but when I submit the code, I get wrong answer. In other side, I've check this code with numbers of integers and I've get the correct answer.
#include <iostream>
using namespace std;
int main() {
unsigned long long cc = 0;
cin >> cc;
while (cc != 0) {
unsigned long long sum = 0;
while (cc > 0) {
sum += cc % 10;
cc = cc / 10;
if (cc == 0 && sum > 9) { cc = sum; sum = 0; }
}
cout << sum;
cin >> cc;
cout << endl;
}
}
Can you please help me?!
Thank you.
The problem is that the input integer is larger than what would fit in an unsigned long long.
Therefore, you need to read the number as a string, and then calculate the digit sum from the string.
The following code will work:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string inStr;
while(cin >> inStr && inStr != "0")
{
unsigned long long cc = 0;
for(string::const_iterator it = inStr.begin(); it!=inStr.end(); ++it)
{
cc += *it - '0';
}
unsigned long long sum = 0;
do
{
while (cc)
{
sum += cc % 10;
cc = cc / 10;
}
cc = sum;
sum = 0;
}while(cc > 9);
cout << cc << endl;
}
return 0;
}
I wonder why anyone didn't post this yet... :P
the function returns the answer :)
int Digital_root(int a) {
return a%9==0 ? 9:a%9;
}
Probably the problem is in that number might contain more than 2 digits and in this case such a modification is necessary:
int main() {
unsigned long long cc = 0;
cin >> cc;
unsigned long long sum = 0;
while (cc > 0) {
sum += cc % 10;
cc = cc / 10;
if ( sum > 9) { cc = sum; sum = 0; }
^
// cc == 0 will fail
}
cout << sum;
}
It's not perfect code, but can work
int a = 0;
int b = 0;
while (true)
{
cout << endl << "a: ";
cin >> a;
if (!a) break;
do
{
while (a)
{
b += a%10;
a /= 10;
}
a = b;
b = 0;
}
while (a > 9);
cout << endl<< "root: " << a;
The task really asks for the remainder under division by 9.
Reason: Since 10 mod 9 == 1 and thus also 10^k mod 9 == 1, the sum of decimal digits has the same remainder under division by 9 as the number itself. Repeated sums of digits do not change the remainder, so the decimal digital root of some n is the same as n mod 9 or computing the digital sum of n modulo 9.
Reducing the code of riklund to this basic task gives
#include <iostream>
#include <string>
using namespace std;
int main() {
string inStr;
while(cin >> inStr && inStr != "0") {
unsigned int cc = 0; // need only 5 bit for cc in this computation
for(string::const_iterator it = inStr.begin(); it!=inStr.end(); ++it) {
cc += *it - '0';
cc %=9;
}
cout << cc << endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
for (int i = 0; ; i++)
{
unsigned long int x,sum=0;
cin >> x;
if (x == 0)
break;
if (x <= 9)
{
sum = x;
goto z;
}
while (x > 9)
{
while (x != 0)
{
sum = sum + (x%10);
x = x / 10;
}
if (sum > 9)
{
x = sum;
sum = 0;
}
}
z:
cout << sum <<"\n";
}
}
//digital roots.cpp~KAUSHIK
#include<iostream>
using namespace std;
int sum(int n)
{
int sum=0,r;
for (;n>0;)
{
r=n%10;
sum=sum+r;
n=n/10;
}
return sum;
}
int main()
{
int n;
cout<<"enter any number"<<endl;
cin>>n;
int a=n;
n=sum(n);
if((n/10)!=0)
{
n=sum(n);
cout<<"the digital root of "<<a<<" is"<<n;
}
else cout<<"the digital root of "<<a<<" is"<<n;
return 0;
}
it works for small integers
#include <iostream>
using namespace std;
int main()
{
unsigned long long input;
while (true)
{
cin >> input;
if (input == 0) break;
input = input - (9 * ((input - 1) / 9));
cout << input << endl;
}
return 0;
}
it works simple copy that in main(), sorry for my english.
int a = 39;
int b = 0;
do
{
while (a)
{
b += a%10;
a /= 10;
}
a = b;
b = 0;
}
while (a > 9);