C++ sum of odd digit - c++

I have created a program in which the function can add all the odd digits; however, I would like print out all the odd digits, for example, sum_odd_digits(2139) return 1+3+9 = 13 while sum_odd_digits(1024) return 1.
#include <iostream>
using namespace std;
int sum_odd_digits(unsigned int i){
unsigned int a =0;
while ((i !=0)&&(i%2 !=0)){
a +=i%10;
i/=10;
}
cout << a;
}
int main(){
sum_odd_digits(2139);
}
Anyone can give me some tips for printing out odd digits?
Thanks for your help

This is it:
int sum_odd_digits(unsigned int i){
unsigned int a = 0;
while (i != 0){
if ( i % 2 == 1 )
cout << i % 10 << ' ';
a += i % 10;
i /= 10;
}
return a;
}
It looks through all digits, and if digit is odd it prints it. It return digits sum.

You're on the right track. The following example separates the digits of a number, and prints them if they are odd.
Code Listing
#include<stdio.h>
int main(){
int num,temp,factor=1;
printf("Enter a number: ");
scanf("%d",&num);
temp=num;
while(temp){
temp=temp/10;
factor = factor*10;
}
printf("The odd digits of the number are: ");
while(factor>1){
factor = factor/10;
switch (num/factor) {
case 1:
case 3:
case 5:
case 7:
case 9:
printf("%d ",num/factor);
break;
}
num = num % factor;
}
return 0;
}

while ((i !=0)&&(i%2 !=0))
This will stop as soon as either condition is false; when i becomes zero, or when the value is even. However, you don't want to stop when you find the first even value, you want to continue testing digits and only stop when i becomes zero. So this should be structured as
while (i != 0) {
if (i % 2 != 0) {
// final digit is odd
a += i%10;
}
i/=10;
}
You could compress the first an last lines into a for loop if you like
for (; i != 0; i /= 10)

Related

For reversing a number in C++ which ends with zeros

I want to write a program for reversing a number. For reversing a number like 2300 to 32 so that the ending zeros are not printed, I found this method:
#include<iostream>
using namespace std;
int main()
{
int l;
cin>>l;
bool leading = true;
while (l>0)
{
if ((l%10==0)&& (leading==true))
{
l /= 10;
leading = false; // prints 032 as output
continue;
}
// leading = false; this prints correct 32
cout<<l%10;
l /= 10;
}
return 0;
}
The instruction of assigning boolean leading false inside the if statement is not giving a valid answer, but I suppose assigning it false should give 32 as output whether we give it outside or inside if statement as its purpose is just to make it false once you get the last digit to be a non zero.
Please tell the reason of difference in outputs.
The reason for the difference in output is because when you make leading = false inside the if statement, you are making it false right after encountering the first zero. When you encounter the remaining zeroes, leading will be false and you will be printing it.
When you make leading = false outside the if statement, you are basically waiting till you encounter all zeroes before making it false.
If you are looking to reverse a number, this is the well known logic to do so:
int reverse(int n)
{
int r; //remainder
int rev = 0; //reversed number
while(n != 0)
{
r = n%10;
rev = rev*10 + r;
n /= 10;
}
return rev;
}
EDIT:
The above code snippet is fine if you just want to understand the logic to reverse a number. But if you want to implement the logic anywhere you have to make sure you handle integer overflow problems (the reversed number could be too big to be stored in an integer!!).
The following code will take care of integer overflow:
int reverse(int n)
{
int r; //remainder
int rev = 0; //reversed number
while(n != 0)
{
r = n%10;
if(INT_MAX/10 < rev)
{
cout << "Reversed number too big for an int.";
break;
}
else if(INT_MAX-r < rev*10)
{
cout << "Reversed number too big for an int.";
break;
}
rev = rev*10 + r;
n /= 10;
}
if(n != 0)
{
//could not reverse number
//take appropriate action
}
return rev;
}
First, rewrite without continue to make the flow clearer,
while (l > 0)
{
if ((l % 10 == 0) && (leading == true))
{
l /= 10;
leading = false; // prints 032 as output
}
else
{
// leading = false; this prints correct 32
cout << l % 10;
l /= 10;
}
}
and move the division common to both branches out of the conditional,
while (l > 0)
{
if ((l % 10 == 0) && (leading == true))
{
leading = false; // prints 032 as output
}
else
{
// leading = false; this prints correct 32
cout << l % 10;
}
l /= 10;
}
and now you see that the only difference between the two is the condition under which the assignment leading = false happens.
The correct version says, "If this digit is non-zero or a non-leading zero, remember that the next digit is not a leading zero, and print this digit. Then divide."
Your broken version says, "If this is a leading zero, the next digit is not a leading zero." which is pretty obviously not the case.
Just try this ,
#include <iostream>
using namespace std;
int main() {
int n, reversedNumber = 0, remainder;
cout << "Enter an integer: ";
cin >> n;
while(n != 0) {
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
cout << "Reversed Number = " << reversedNumber;
return 0;
}
Working for me...
When reversing digits of numbers or generally when working with digits and the actual
value does not matter then treating the number as an array of digits is simpler than working with the whole int. How to treat a number as an array of digits conveniently? std::string:
#include <iostream>
#include <string>
#include <sstream>
int reverse_number(int x) {
std::string xs = std::to_string(x);
std::string revx{ xs.rbegin(),xs.rend()};
std::stringstream ss{revx};
int result;
ss >> result;
return result;
}
int main() {
std::cout << reverse_number(123) << "\n";
std::cout << reverse_number(1230) << "\n";
}
std::to_string converts the int to a std::string. std::string revx{ xs.rbegin(),xs.rend()}; constructs the reversed string by using reverse iterators, and eventually a stringstream can be used to parse the number. Output of the above is:
321
321

Recursive Digit Sum

I was trying to solve this problem on hackerrank. But I got some problem. Specific problem is:
For example:
The sum of digits 9875 will be calculate as: sum(9875) = 9+8+7+5 = 29. sum(29) = 11. sum(11) = 2. (Using recursive function).
In my test case, (n ='9875', k=4) the number p is created by concatenating the string n k times so the initial p = 9875987598759875 ( the string '9875' repeat 4 times ).
But when i code this test case, it doesn't work. Here is my source code:
int SuperDigit(long n){
long sum =0;
if(n==0) return 0;
else{
return sum= sum +(n%10 + SuperDigit(n/10));
}
if(sum>10){
return (sum%10 + SuperDigit(sum/10));
}
}
int main(){
string n;cin>>n;
int T;cin>>T;
string repeat;
for(int i=0; i <T;i++){
repeat += n;
}
cout<<repeat;
long x=0;
stringstream geek(repeat);
geek>>x;
long sum = SuperDigit(x);
printf("\n%ld ",sum);
for(int i=0;i<10;i++){
if(sum>=10){
sum = SuperDigit(sum);
}
else{
break;
}
}
printf("\n%ld ",sum);
}
If i try: n = '123' and k =3 (Expected output: 9)
My output will be correct, here is my output for this test case:
123 3
123123123
18
9
But when i try n = '9875' and k = 4 (Expected output: 8)
My output will be wrong:
9875 4
9875987598759875
46
1
As you can see in this test case, the first sum of all digits must be 116. But mine only show 46. Can anyone explain for me? Thanks a lot!
In your current code you return prematurely in
if(n==0) return 0;
else{
return sum= sum +(n%10 + SuperDigit(n/10));
}
Imagine that n == 89 so n%10 returns 9 and SuperDigit(n/10) returns 8 and you have 17 as an answer (when 8 is expected).
You can put it as
int SuperDigit(long n) {
int result = 0;
/* We compute digital root (sum of digits) */
for (long number = n; number != 0; number /= 10)
result += (int) (number % 10);
/* if result is out of range [-9..9]
we compute digital root again from the answer */
if (result < -9 || result > 9)
result = SuperDigit(result);
return result;
}
You can simplify your program as shown below. Since you want to find the sum recursively, the below program shows one possible way of doing it.
Version 1: Using recursive function
#include <iostream>
int findDigit(int passed_num, int currentSum)
{
int lastDigit;
if (passed_num == 0) {
return currentSum;
}
// find the last didit
lastDigit = passed_num % 10;
currentSum+= lastDigit;
//call findDigit() repeatedly
currentSum = findDigit(passed_num / 10, currentSum);
std::cout<<lastDigit<<" ";
return currentSum;
}
int main()
{
std::cout << "Enter a number: ";
int input_num, sum;
std::cin>>input_num;
sum = findDigit(input_num, 0);
std::cout<<"sum is: "<<sum<<std::endl;
std::cout << "Enter another number: ";
std::cin>>input_num;
sum = findDigit(input_num, 0);
std::cout<<"sum is: "<<sum<<std::endl;
return 0;
}
Note there are simpler(other) ways of finding the sum without recursively. One such way is shown below:
Version 2: Using loop
#include <string>
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int individual_number = 0, sum = 0;//these are local built in types so initialize them
std::string input_num;
std::cin >> input_num;
for(char c : input_num)
{
individual_number = c -'0';
std::cout<<individual_number<<" ";
sum+= individual_number;
}
std::cout<<"total amount: "<<sum<<std::endl;
// std::cout<<"The sum comes out to be: "<<sum<<std::endl;
return 0;
}

C++ Gapful Numbers Crashing

I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?
Here's my code:
#include<math.h>
#include<stdlib.h>
using namespace std;
void gapful(int);
bool gapCheck(int);
int main(){
int n;
cout<<"Enter a top number: ";
cin>>n;
gapful(n);
system("pause");
return 0;
}
void gapful(int og){
for(int i=0; i<=og; i++){
fflush(stdin);
if(gapCheck(i)){
cout<<i<<" ";
}
}
}
bool gapCheck(int n){
int digits=0;
int n_save,n1,n2,n3;
if(n<100){
return false;
}
else{
n_save=n;
while(n>10){
n/=10;
digits++;
}
digits++;
n=n_save;
n1=n/pow(10, digits);
n2=n%10;
n3=n1*10 + n2;
if(n%n3 == 0){
return true;
}
else{
return false;
}
}
}
I'm open to any suggestions and comments, thank you. :)
For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?
We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.
So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.
#include<math.h>
#include <iostream>
using namespace std;
void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);
int main(){
int n;
cout<<"Enter a top number: " << endl;
cin>>n;
gapful(n);
return 0;
}
void gapful(int og){
for(int i=1; i<=og; ++i){
if(gapCheck(i)){
cout<<i << '-' <<endl;
}
}
}
int getDigits(int number) {
int digitCount = 0;
while (number >= 10) {
++digitCount;
number /= 10;
}
return ++digitCount;
}
int digitAt(int number,int digit) {
int numOfDigits = getDigits(number);
int curDigit = 0;
if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
while (numOfDigits != digit) { //Count back to the digit requested
number /=10;
numOfDigits -=1;
}
curDigit = number%10; //Get the current digit to be returned.
} else {
throw "Digit requested is out of range!";
}
return curDigit;
}
bool gapCheck(int n){
int digitsN = getDigits(n);
if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
return false;
}
int first = digitAt(n,1) * 10; //Get the first number in the 10s place
int second = digitAt(n,digitsN); //Get the second number
int total = first + second; //Add them
return n % total == 0; //Return whether it evenly divides
}

How to reverse a negative integer recursively in C++?

I am working on some recursion practice and I need to write a program that reverse the input of an integer
Example of input : cin >> 12345; The output should be 54321
but if that integer is negative the negative sign needs to be appended to only the first number.
Example of input : cin >> -1234; output -4321
I am having a hard time getting my program to adapt to the negative numbers. The way I have it set up if I run
Example of test : 12345 I get the right output 54321
So my recursion and base are successful. But if I run a negative I get
Example of test : -12345 I get this for a reason I don't understand -5-4-3-2 1
#include<iostream>
using namespace std;
void reverse(int);
int main()
{
int num;
cout << "Input a number : ";
cin >> num;
reverse(num);
return 0;
}
void reverse(int in)
{
bool negative = false;
if (in < 0)
{
in = 0 - in;
negative = true;
}
if (in / 10 == 0)
cout << in % 10;
else{
if (negative == true)
in = 0 - in;
cout << in % 10;
reverse(in / 10);
}
}
To reverse a negative number, you output a - and then reverse the corresponding positive number. I'd suggest using recursion rather than state, like this:
void reverse(int in)
{
if (in < 0)
{
cout << '-';
reverse(-in);
}
else
{
// code to recursively reverse non-negative numbers here
}
}
Split the reverse function into two parts: the first part just prints - (if the input is negative) and then calls the second part, which is the recursive code you have. (You don't need any of the if (negative) ... handling any more, since the first part already handled it.)
Incidentally, if (bool_variable == true) ... is overly verbose. It's easier to read code if you say something like if (value_is_negative) ....
Your recursive function doesn't hold state. When you recurse the first time, it prints the '-' symbol but every time you send back a negative number to the recursion, it runs as if it is the first time and prints '-' again.
It's better to print '-' first time you see a negative number and send the rest of the number as a positive value to the recursion.
#include<iostream>
using namespace std;
void reverse(int);
int main()
{
int num;
cout << "Input a number : ";
cin >> num;
reverse(num);
return 0;
}
void reverse(int in)
{
bool negative = false;
if (in < 0)
{
in = 0 - in;
negative = true;
}
if (in / 10 == 0)
cout << in % 10;
else{
if (negative == true) {
cout << '-';
negative = false;
}
cout << in % 10;
reverse(in / 10);
}
}
int reverse(long int x) {
long int reversedNumber = 0, remainder;
bool isNegative = false;
if (x <0){
isNegative = true;
x *= -1;
}
while(x > 0) {
remainder = x%10;
reversedNumber = reversedNumber*10 + remainder;
x= x/10;
}
if (isNegative) {
if (reversedNumber > INT_MAX){
return 0;
}
else
return reversedNumber*(-1);
}
else
{
if (reversedNumber > INT_MAX){
return 0;
}
else
return reversedNumber;
}
}

Prime number C++ program

I am not sure whether I should ask here or programmers but I have been trying to work out why this program wont work and although I have found some bugs, it still returns "x is not a prime number", even when it is.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i < b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
break;
}
//Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
else if ((a % i != 0) && (i == a -1)) {
return (1);
break;
}
}
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}
Sorry if this is too localised (in which case could you suggest where I should ask such specific questions?)
I should add that I am VERY new to C++ (and programming in general)
This was simply intended to be a test of functions and controls.
i can never be equal to a - 1 - you're only going up to b - 1. b being a/2, that's never going to cause a match.
That means your loop ending condition that would return 1 is never true.
In the case of a prime number, you run off the end of the loop. That causes undefined behaviour, since you don't have a return statement there. Clang gave a warning, without any special flags:
example.cpp:22:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
1 warning generated.
If your compiler didn't warn you, you need to turn on some more warning flags. For example, adding -Wall gives a warning when using GCC:
example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function
Overall, your prime-checking loop is much more complicated than it needs to be. Assuming you only care about values of a greater than or equal to 2:
bool primetest(int a)
{
int b = sqrt(a); // only need to test up to the square root of the input
for (int i = 2; i <= b; i++)
{
if (a % i == 0)
return false;
}
// if the loop completed, a is prime
return true;
}
If you want to handle all int values, you can just add an if (a < 2) return false; at the beginning.
Your logic is incorrect. You are using this expression (i == a -1)) which can never be true as Carl said.
For example:-
If a = 11
b = a/2 = 5 (Fractional part truncated)
So you are running loop till i<5. So i can never be equal to a-1 as max value of i in this case will be 4 and value of a-1 will be 10
You can do this by just checking till square root. But below is some modification to your code to make it work.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i <= b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
}
}
//this return invokes only when it doesn't has factor
return 1;
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
return 0;
}
check this out:
//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;
int main()
{
int a = 2; //start from 2
long long int b = 1000; //ends at 1000
for (int i = a; i <= b; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j)) //Condition for not prime
{
break;
}
if (j==i) //condition for Prime Numbers
{
cout << i << endl;
}
}
}
}
main()
{
int i,j,x,box;
for (i=10;i<=99;i++)
{
box=0;
x=i/2;
for (j=2;j<=x;j++)
if (i%j==0) box++;
if (box==0) cout<<i<<" is a prime number";
else cout<<i<<" is a composite number";
cout<<"\n";
getch();
}
}
Here is the complete solution for the Finding Prime numbers till any user entered number.
#include <iostream.h>
#include <conio.h>
using namespace std;
main()
{
int num, i, countFactors;
int a;
cout << "Enter number " << endl;
cin >> a;
for (num = 1; num <= a; num++)
{
countFactors = 0;
for (i = 2; i <= num; i++)
{
//if a factor exists from 2 up to the number, count Factors
if (num % i == 0)
{
countFactors++;
}
}
//a prime number has only itself as a factor
if (countFactors == 1)
{
cout << num << ", ";
}
}
getch();
}
One way is to use a Sieving algorithm, such as the sieve of Eratosthenes. This is a very fast method that works exceptionally well.
bool isPrime(int number){
if(number == 2 || number == 3 | number == 5 || number == 7) return true;
return ((number % 2) && (number % 3) && (number % 5) && (number % 7));
}