Fastest way to sum 3 numbers digits - c++

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;
}

Related

Sum of digits in 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

Is there any better way to do this in C++? Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

This is what I came up with
#include <iostream>
using namespace std;
int serialNumber = 1;
Would recursion be better?
int factorial(int n)
{
int k=1;
for(int i=1;i<=n;++i)
{
k=k*i;
}
return k;
}
How can I go about doing this in a single for loop?
Or is this the best way?
int main()
{
int a;
int b;
int c;
int fact1;
int fact2;
int fact3;
for (a=1;a < 11;a++)
{
fact1 = factorial(a);
for (b=1;b < 11;b++)
{
fact2 = factorial(b);
for (c=1;c < 11;c++)
{
fact3 = factorial(c);
cout << serialNumber << " : ";
int LHS = fact1 + fact2 + fact3;
if (LHS == a * b * c)
{
cout << "Pass:" <<" "<< a << " & " << b << " & " << c << endl;
}
else
{
cout << "Fail" <<endl;
}
serialNumber++;
}
c = 1;
}
b = 1;
}
return 0;
}
I am being forced to add more none code into it.
Thanks for the help!
Don't know if this is helps,but>
check for minimum of A,B,C
A!+B!+C! = (min(A,B,C)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))
So, you can calculate the minimum factorial and than re-use it for calculating others.
On the other hand, you can calculate only the maximum factorial and store its results in the array, and re-use pre-calculated values for finding factorial of smaller numbers
Other implication is that the minimum number can be reduced
restfact1 * restfact2 = ((min-1)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))
Part of the question was how can this be done in a single loop and this is one way to do that.
I don't think this is a better way of doing it, but the question was asked:
constexpr int bound = 10;
int Factorials[bound + 1];
for (int i = 1; i <= bound; ++i) Factorials[i] = Factorial(i);
for (int i = 0; i < bound * bound * bound; ++i) {
int s = i + 1;
int a = i;
int c = 1 + a % bound;
a /= bound;
int b = 1 + a % bound;
a /= bound;
++a;
cout << s << " : ";
int LHS = Factorials[a] + Factorials[b] + Factorials[c];
if (LHS == a * b * c)
...
}

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;
}

convert a number from base-10 to another base

I tried the following code to convert a number from base-10 to another base. it works if there is no zero(0) in the destination base. check 79 and 3 and it properly prints 2221 which is correct.
now try number 19 and 3, the result would be 21 instead of 201 which indicates something's wrong.
int x, y, a = 0, i, t, j;
cout << "enter two numbers" << endl;
cin >> x >> y; // x as the number in base-10 and x, as the destination base
a = x;
while (x >= y)
{
t = 1;
for (i = 0; x > y; i++)
{
x /= y;
}
cout << x;
for (j = 0; j < i; j++)
{
t *= y;
}
a = a - (t*x);
x = a;
}
cout << x<<endl;
Using a recursive function is easier than using a while loop for what you are trying to accomplish.
Here's working program.
#include <iostream>
void printInBase(int x, int y)
{
if ( x < y )
{
std::cout << x;
return;
}
int rem = x%y;
printInBase(x/y, y);
std::cout << rem;
}
int main()
{
int x, y;
std::cout << "enter two numbers" << std::endl;
std::cin >> x >> y; // x as the number in base-10 and x, as the destination base
printInBase(x, y);
std::cout << '\n';
}
int x, y, a = 0, i, t, j;
cout << "enter two numbers" << endl;
cin >> x >> y; // x as the number in base-10 and x, as the destination base
a = x;
t = 1;
while (x >= t*y)
{
t = t * y;
}
while (t)
{
cout << x/t << ' ';
x -= t*(x/t);
t /= y;
}
cout << '\n';
basically you weren't keeping track of what digit you were printing out, and your code can't tell when it would need leading zeroes. You could fix that by printing something like 2*(3^2) + 1*(3^0) or by figuring out how many digits you need in advance as I did in the above code.
Despite it could work, there is something conceptually wrong in this approach: you are essentially confusing numbers (the subject of arithmetic operations) with their textual representation (the sequence of digits used to represent them).
The type int -by an external point of view- does not have a "base" (int will most likely have a base-2 internal representation, that's functional to the purpose to be manipulated by the arithmetic unit circuitry): it's just a thing to be added, subtracted multilyed, divided, and-ed, xor-ed etc.
When you do cout << a what << do, is convert the a number to a sequence of digit representing it into something readable. By default it happens to do it in base-10 digit represented as ASCII characters ('0'...'9').
What you are doing is convert a number into another number whose decimal representation resemble the base you are mapping. It can work in printing, but there is no arithmetic that can work with it. So int is not a correct representation for them.
What you need is a different text-converter: something that takes an int and another int specifying a base, and spits out the characters to represent your number.
Think to a class like
class based
{
int n, base;
public:
based(int num, int base) :n(num), base(base) {}
friend std::ostream& operator<<(std::ostream& out, const based& x);
};
to be used as
std::cout << bsed(79,3) << ' ' << based(19,3) << std::endl;
Now
std::ostream& operator<<(std::ostream& out, const based& x)
{
static const size_t N = 8*sizeof(int)+2; //base 2 is the widest, and is 32 or 64 + 2
char buff[N]; //keep space for sign + base2 + terminator
size_t X = N-1; //current writing character position
buff[X] = 0; //terminating char
--X; //prepare next left character
int n = x.n; //we will work on n
bool neg = (n<0); //keep negative sign
if(neg) n=-n; //and work always with posiotives
while(n) //we will reduce n down to 0
{
int digit = n%x.base; //mod is the last digit
n /= x.base; //next to the left
buff[X] = (digit<10)? char(digit+'0'): char(digit-10+'A');
--X; //next char
}
if(neg) buff[X] = '-';
else ++X; //no sign
out << buff+X << '(' << x.base << ')'; //the text from the point we reach towards left
return out;
}
This will output 2221(3) 201(3).
There is also a more portable way to do char(digit+'0') etc. but considering normal digits, that's not more of what is needed.
My answer.
Will also work on floating point numbers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void radix(char *strNum, int base);
int main ()
{
radix("215.75", 8);
return 0;
}
void swap(char *a, char *b)
{
char temp = *a;
*a = *b;
*b = temp;
}
void radix(char *strNum, int base)
{
char res[100]={0}, tmp[100]={0}, floPoint[100]={0}, *p = 0, *q = 0;
int inum = 0, digitAfterDot = 3;
float fnum = 0.0;
if(strchr(strNum, '.'))
{
p = strNum + strcspn(strNum, ".");
fnum = atof(p);
}
inum = atoi(strNum);
for(p = res; inum; inum /= base, p++)
*p = (inum % base) + '0';
*p = 0;
if(fnum != 0.0)
{
p = floPoint;
*p++ = '.';
for(fnum *= base; digitAfterDot--; p++, fnum *= base)
{
sprintf(tmp, "%f", fnum);
inum = atoi(tmp);
fnum -= inum;
*p = inum + '0';
}
*p = 0;
}
for(p = res, q = res+strlen(res)-1; p < q; p++, q--)
swap(p, q);
strcat(res, floPoint);
puts(res);
}

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);