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);
Related
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;
}
I'm trying to get all prime numbers in the range of 2 and the entered value using this c++ code :
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) {
result = i % b;
if (result == 0) {
result = b;
break;
}
}
cout << result<< endl <<;
}
}
the problem is that I think am getting close to the logic, but those threes and twos keep showing up between the prime numbers. What am I doing wrong?
I've fixed your code and added comments where I did the changes
The key here is to understand that you need to check all the numbers smaller then "i" if one of them dividing "i", if so mark the number as not prime and break (the break is only optimization)
Then print only those who passed the "test" (originally you printed everything)
#include <iostream>
using namespace std;
#include<iostream>
using namespace std;
int main()
{
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool isPrime = true; // Assume the number is prime
for (int b = 2; b < i; b++) { // Run only till "i-1" not "num"
result = i % b;
if (result == 0) {
isPrime = false; // if found some dividor, number nut prime
break;
}
}
if (isPrime) // print only primes
cout << i << endl;
}
}
Many answers have been given which explains how to do it. None have answered the question:
What am I doing wrong?
So I'll give that a try.
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) { // wrong: use b < i instead of b <= num
result = i % b;
if (result == 0) {
result = b; // wrong: why assign result the value of b?
// just remove this line
break;
}
}
cout << result<< endl <<; // wrong: you need a if-condtion before you print
// if (result != 0) cout << i << endl;
}
}
You have multiple errors in your code.
Simplest algorithm (not the most optimal though) is for checking whether N is prim is just to check whether it doesn't have any dividers in range [2; N-1].
Here is working version:
int main() {
int num = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool bIsPrime = true;
for (int b = 2; bIsPrime && b < i; b++) {
if (i % b == 0) {
bIsPrime = false;
}
}
if (bIsPrime) {
cout << i << endl;
}
}
}
I would suggest pulling out the logic of determining whether a number is a prime to a separate function, call the function from main and then create output accordingly.
// Declare the function
bool is_prime(int num);
Then, simplify the for loop to:
for (int i = 2; i <= num; i++) {
if ( is_prime(i) )
{
cout << i << " is a prime.\n";
}
}
And then implement is_prime:
bool is_prime(int num)
{
// If the number is even, return true if the number is 2 else false.
if ( num % 2 == 0 )
{
return (num == 2);
}
int stopAt = (int)sqrt(num);
// Start the number to divide by with 3 and increment it by 2.
for (int b = 3; b <= stopAt; b += 2)
{
// If the given number is divisible by b, it is not a prime
if ( num % b == 0 )
{
return false;
}
}
// The given number is not divisible by any of the numbers up to
// sqrt(num). It is a prime
return true;
}
I can pretty much guess its academic task :)
So here the think for prime numbers there are many methods to "get primes bf number" some are better some worse.
Erosthenes Sieve - is one of them, its pretty simple concept, but quite a bit more efficient in case of big numbers (like few milions), since OopsUser version is correct you can try and see for yourself what version is better
void main() {
int upperBound;
cin >> upperBound;
int upperBoundSquareRoot = (int)sqrt((double)upperBound);
bool *isComposite = new bool[upperBound + 1]; // create table
memset(isComposite, 0, sizeof(bool) * (upperBound + 1)); // set all to 0
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) { // if not prime
cout << m << " ";
for (int k = m * m; k <= upperBound; k += m) // set all multiplies
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++) // print results
if (!isComposite[m])
cout << m << " ";
delete [] isComposite; // clean table
}
Small note, tho i took simple implementation code for Sive from here (writing this note so its not illegal, truth be told wanted to show its easy to find)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So my question is how to efficiently write a program where in we are able to take multiple inputs (the amount of inputs given is determined by the user) and then give the outputs at once. Lets consider a program which gives gives the sum of its digits. Eg - 12345 = 15.
//Single input single output
#include <iostream>
using namespace std;
int main()
{
int T, N;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
cout << "Enter the value of N : " << endl;
while (T > 0)
{
cin >> N;
int ans = 0,temp1,temp2;
while(N!=0)
{
temp1= N %10;
N = (N - temp1)/10;
ans = ans + temp1;
}
cout << ans << endl;
T--;
}
return 0;
}
// Taking in all inputs then giving out all outputs ( Not working properly)
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase, int t);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int *Ans(new int[T]);
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i, T);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
delete[] Ans;
return 0;
}
int SumCal(int Number, int TestCase, int t)
{
int temp1, temp2 = 0;
int *AnsTemp(new int[t]);
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
AnsTemp[TestCase] = (temp1 + temp2);
while (temp2 > 10)
{
AnsTemp[TestCase] = (AnsTemp[TestCase] + temp1);
temp2 = temp2 / 10;
temp1 = temp1 % 10;
}
return AnsTemp[TestCase];
delete[] AnsTemp;
}
// This will work properly for multiple inputs multiple outputs
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int Ans[1000] = {};
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
return 0;
}
int SumCal(int Number, int TestCase)
{
int temp1, temp2 = 0;
int ans;
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
ans = (temp1 + temp2);
while (temp2 > 10)
{
ans = (ans + temp1);
temp2 = temp2 / 10;
temp1 = temp2 % 10;
}
return ans;
}
These are the codes I could think of. The first one is a simple one, which takes in an input and then gives out a output. In the second one I tried to use dynamic memory allocation but the program gives error. ( I know I haven't made proper use of * and & in it but I already tried using it in various manners and failed). The third program is successful but as we are setting up a large constraint value to the array, (i.e int Ans[1000]) it makes the program a bit inefficient.
So my question is how would one dynamically allocate memory during runtime successfully to take in multiple inputs and then give multiple outputs at once.
It's very hard to work with your code. I just took the 1st example, minimized the code and did what you should have done:
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int T;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
int *buf = new int[T](); // buffer to hold the answers
for(int i = 0; i < T; ++i)
{
int N;
cout << "Enter the value of N : " << endl;
cin >> N;
while(N)
{
buf[i] += N % 10; // calculate on the buffer element
N /= 10;
}
}
for(int i = 0; i < T; ++i)
cout << buf[i] << endl; // print the buffer
delete [] buf; // delete buffer
return 0;
}
There's not much to do for managing the dynamically allocated array here, but take a look at std::vector and its uses.
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 8 years ago.
Improve this question
I made a function that converts binary numbers to decimals, but if i go to high on the binary numbers, it just returns 256??? What could cause this? I'm using int variables. Any help would be really appreciated
#include <iostream>
using namespace std;
int FromBin (int n)
{
int increment;
int Result;
increment = 1;
Result = 0;
while(n != 0)
{
if (n % 10 == 1){
Result = Result+increment;
n = n-1;
}
n = n/10;
increment = increment*2;
}
cout<<Result;
}
void ToBin(int n)
{
if (n / 2 != 0) {
ToBin(n / 2);
}
cout<<n % 2;
}
int main()
{
int choice;
int n;
cout<<"Choose a function: press 0 for decimals to binary, press 1 for binary to decimal\n";
cin>>choice;
if (choice == 0){
cout<<"Enter a number: \n";
cin>>n;
ToBin(n);
}
else if (choice == 1){
cout<<"Enter a number: \n";
cin>>n;
FromBin(n);
}
else{
cout<<"Invalid input";
}
}
I'm new to C++ so I don't understand this... :/
This is a cool program you got going on here...
This is what I found for a possible solution to your problem...
/* C++ program to convert binary number into decimal */
#include <iostream>
using namespace std;
int main()
{
long bin, dec = 0, rem, num, base = 1;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
while (num > 0)
{
rem = num % 10;
dec = dec + rem * base;
base = base * 2;
num = num / 10;
}
cout << "The decimal equivalent of " << bin << " : " << dec << endl;
return 0;
}
This is what I think you were shooting for. You can handle larger numbers by switching from int to long.
long fromBin(long n)
{
long factor = 1;
long total = 0;
while (n != 0)
{
total += (n%10) * factor;
n /= 10;
factor *= 2;
}
return total;
}
Live demo
From your comment I can see that you are trying to use it on a number that is just too large for an int variable. Look for limits, as for int I found that maximal value is 2147483647.
I have an integer:
int iNums = 12476;
And now I want to get each digit from iNums as integer. Something like:
foreach(iNum in iNums){
printf("%i-", iNum);
}
So the output would be: "1-2-4-7-6-".
But i actually need each digit as int not as char.
Thanks for help.
void print_each_digit(int x)
{
if(x >= 10)
print_each_digit(x / 10);
int digit = x % 10;
std::cout << digit << '\n';
}
Convert it to string, then iterate over the characters. For the conversion you may use std::ostringstream, e.g.:
int iNums = 12476;
std::ostringstream os;
os << iNums;
std::string digits = os.str();
Btw the generally used term (for what you call "number") is "digit" - please use it, as it makes the title of your post much more understandable :-)
Here is a more generic though recursive solution that yields a vector of digits:
void collect_digits(std::vector<int>& digits, unsigned long num) {
if (num > 9) {
collect_digits(digits, num / 10);
}
digits.push_back(num % 10);
}
Being that there are is a relatively small number of digits, the recursion is neatly bounded.
Here is the way to perform this action, but by this you will get in reverse order.
int num;
short temp = 0;
cin>>num;
while(num!=0){
temp = num%10;
//here you will get its element one by one but in reverse order
//you can perform your action here.
num /= 10;
}
I don't test it just write what is in my head. excuse for any syntax error
Here is online ideone demo
vector <int> v;
int i = ....
while(i != 0 ){
cout << i%10 << " - "; // reverse order
v.push_back(i%10);
i = i/10;
}
cout << endl;
for(int i=v.size()-1; i>=0; i--){
cout << v[i] << " - "; // linear
}
To get digit at "pos" position (starting at position 1 as Least Significant Digit (LSD)):
digit = (int)(number/pow(10,(pos-1))) % 10;
Example: number = 57820 --> pos = 4 --> digit = 7
To sequentially get digits:
int num_digits = floor( log10(abs(number?number:1)) + 1 );
for(; num_digits; num_digits--, number/=10) {
std::cout << number % 10 << " ";
}
Example: number = 57820 --> output: 0 2 8 7 5
You can do it with this function:
void printDigits(int number) {
if (number < 0) { // Handling negative number
printf('-');
number *= -1;
}
if (number == 0) { // Handling zero
printf('0');
}
while (number > 0) { // Printing the number
printf("%d-", number % 10);
number /= 10;
}
}
Drawn from D.Shawley's answer, can go a bit further to completely answer by outputing the result:
void stream_digits(std::ostream& output, int num, const std::string& delimiter = "")
{
if (num) {
stream_digits(output, num/10, delimiter);
output << static_cast<char>('0' + (num % 10)) << delimiter;
}
}
void splitDigits()
{
int num = 12476;
stream_digits(std::cout, num, "-");
std::cout << std::endl;
}
I don't know if this is faster or slower or worthless, but this would be an alternative:
int iNums = 12476;
string numString;
stringstream ss;
ss << iNums;
numString = ss.str();
for (int i = 0; i < numString.length(); i++) {
int myInt = static_cast<int>(numString[i] - '0'); // '0' = 48
printf("%i-", myInt);
}
I point this out as iNums alludes to possibly being user input, and if the user input was a string in the first place you wouldn't need to go through the hassle of converting the int to a string.
(to_string could be used in c++11)
I know this is an old post, but all of these answers were unacceptable to me, so I wrote my own!
My purpose was for rendering a number to a screen, hence the function names.
void RenderNumber(int to_print)
{
if (to_print < 0)
{
RenderMinusSign()
RenderNumber(-to_print);
}
else
{
int digits = 1; // Assume if 0 is entered we want to print 0 (i.e. minimum of 1 digit)
int max = 10;
while (to_print >= max) // find how many digits the number is
{
max *= 10;
digits ++;
}
for (int i = 0; i < digits; i++) // loop through each digit
{
max /= 10;
int num = to_print / max; // isolate first digit
to_print -= num * max; // subtract first digit from number
RenderDigit(num);
}
}
}
Based on #Abyx's answer, but uses div so that only 1 division is done per digit.
#include <cstdlib>
#include <iostream>
void print_each_digit(int x)
{
div_t q = div(x, 10);
if (q.quot)
print_each_digit(q.quot);
std::cout << q.rem << '-';
}
int main()
{
print_each_digit(12476);
std::cout << std::endl;
return 0;
}
Output:
1-2-4-7-6-
N.B. Only works for non-negative ints.
My solution:
void getSumDigits(int n) {
std::vector<int> int_to_vec;
while(n>0)
{
int_to_vec.push_back(n%10);
n=n/10;
}
int sum;
for(int i=0;i<int_to_vec.size();i++)
{
sum+=int_to_vec.at(i);
}
std::cout << sum << ' ';
}
The answer I've used is this simple function:
int getDigit(int n, int position) {
return (n%(int)pow(10, position) - (n % (int)pow(10, position-1))) / (int)pow(10, position-1);
}
Hope someone finds this helpful!
// Online C++ compiler to run C++ program online
#include <iostream>
#include <cmath>
int main() {
int iNums = 123458;
// int iNumsSize = 5;
int iNumsSize = trunc(log10(iNums)) + 1; // Find length of int value
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
// The pow() function returns the result of the first argument raised to
the power of the second argument.
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d ",z - x2*10 ); // Print Values
}
return 0;
}
You can do it using a while loop and the modulo operators.
It just gives the digits in the revese order.
int main() {
int iNums = 12476;
int iNum = 0;
while(iNums > 0) {
iNum = iNums % 10;
cout << iNum;
iNums = iNums / 10;
}
}
int a;
cout << "Enter a number: ";
cin >> a;
while (a > 0) {
cout << a % 10 << endl;
a = a / 10;
}
int iNums = 12345;
int iNumsSize = 5;
for (int i=iNumsSize-1; i>=0; i--) {
int y = pow(10, i);
int z = iNums/y;
int x2 = iNums / (y * 10);
printf("%d-",z - x2*10 );
}