Recursive Digit Sum - c++

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

Related

Kickstart 2022 interesting numbers

The question is to find the number of interesting numbers lying between two numbers. By the interesting number, they mean that the product of its digits is divisible by the sum of its digits.
For example: 459 => product = 4 * 5 * 9 = 180, and sum = 4 + 5 + 9 = 18; 180 % 18 == 0, hence it is an interesting number.
My solution for this problem is having run time error and time complexity of O(n2).
#include<iostream>
using namespace std;
int main(){
int x,y,p=1,s=0,count=0,r;
cout<<"enter two numbers"<<endl;
cin>>x>>y;
for(int i=x;i<=y;i++)
{
r=0;
while(i>1)
{
r=i%10;
s+=r;
p*=r;
i/=10;
}
if(p%s==0)
{
count++;
}
}
cout<<"count of interesting numbers are"<<count<<endl;
return 0;
}
If s is zero then if(p%s==0) will produce a divide by zero error.
Inside your for loop you modify the value of i to 0 or 1, this will mean the for loop never completes and will continuously check 1 and 2.
You also don't reinitialise p and s for each iteration of the for loop so will produce the wrong answer anyway. In general limit the scope of variables to where they are actually needed as this helps to avoid this type of bug.
Something like this should fix these problems:
#include <iostream>
int main()
{
std::cout << "enter two numbers\n";
int begin;
int end;
std::cin >> begin >> end;
int count = 0;
for (int number = begin; number <= end; number++) {
int sum = 0;
int product = 1;
int value = number;
while (value != 0) {
int digit = value % 10;
sum += digit;
product *= digit;
value /= 10;
}
if (sum != 0 && product % sum == 0) {
count++;
}
}
std::cout << "count of interesting numbers are " << count << "\n";
return 0;
}
I'd guess the contest is trying to get you to do something more efficient than this, for example after calculating the sum and product for 1234 to find the sum for 1235 you just need to add one and for the product you can divide by 4 then multiply by 5.

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
}

Sum of factoriais to be equal a given number

I'm trying to solve the following problem:
What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)
Example:
Input: 10, Output: 3. (10 = 3! + 2! + 2!)
Input: 25, Output: 2. (25 = 4! + 1!)
My code:
#include<bits/stdc++.h>
using namespace std;
int a;
int rec(int vet){
int count = 0;
a = a - vet;
if(a >= vet){
count++;
rec(vet);
}
count++;
return count;
}
int main(){
int vet[8] = {1}, count = 0;
cin >> a;
for(int i = 2; i <= 8; i++){
vet[i-1] = vet[i-2]*i;
}
for(int i = 7; i >= 0; i--){
if(a < vet[i]){
continue;
}
count += rec(vet[i]);
}
cout << count << endl;
}
My logic:
1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;
2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.
This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.
Can you find where am I wrong? Or if my solution is not good and I should try another approach.
Thanks for the help!
The problem is easily solved by a recursive approach.
Here is checked code:
#include <iostream>
using namespace std;
int factorial(int n) {
return n<=1 ? 1 : n * factorial(n-1);
}
int MinFact(int number)
{
static int num_of_facts;
int a = 1;
if (number)
{
while(factorial(a+1)<=number)a++;
cout << a << "!" << endl;
num_of_facts++;
MinFact((number-factorial(a)));
}
return num_of_facts;
}
int main()
{
int num;
cout << "Enter number" << endl;
cin >> num;
num = MinFact(num);
cout << "Number of factorials: " << num;
return 0;
}
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.
A simple solution would be to replace the rec function as follows
int rec(int vec) {
int count = a / vec;
a = a % vec;
return count;
}
Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.

Print sum to n numbers

Here is my question...
Input a number n from the user. The program should output the sum of all numbers from 1 to n NOT including the multiples of 5.
For example if the user inputs 13 then the program should compute and print the sum of the numbers: 1 2 3 4 6 7 8 9 11 12 13 (note 5,10 are not included in the sum)
i have made the following program but it is not working..
can any one help me THANK YOU in advance...
#include <iostream>
using namespace std;
int main()
{
int inputnumber = 0;
int sum = 0;
int count= 1;
cout<<"Enter the number to print the SUM : ";
cin>>inputnumber;
while(count<=inputnumber)
{
if (count % 5!=0)
{
sum = sum + count;
}
} count = count +1;
cout<<"the sum of the numbers are : "<<sum;
}
You should increment count inside the loop, not outside it:
while(count<=inputnumber)
{
if (count % 5!=0)
{
sum = sum + count;
}
count = count +1; // here
}
Note, by the way, that using a for loop would be much more convenient here. Additionally, sum = sum + count could be shorthanded to sum += count.
for (int count = 1; count <= inputnumber; ++count)
{
if (count % 5 != 0)
{
sum += count;
}
}
You need to put the count+1 inside your while loop. also add !=0 tou your if statement.
while(count<=inputnumber)
{
if (count % 5!=0)
{
sum = sum + count;
}
count = count +1;
}
No need to use a loop at all:
The sum 1..n is
n * (n+1) / 2;
the sum of the multiples of 5 not above n is
5 * m * (m+1) / 2
where m = n/5 (integer devision). The result is therefore
n * (n+1) / 2 - 5 * m * (m+1) / 2
Try this..
In my condition,checks n value is not equal to zero and % logic
int sum = 0;
int n = 16;
for(int i=0 ; i < n ;i++) {
if( i%5 != 0){
sum += i;
}
}
System.out.println(sum);
Let's apply some maths. We'll use a formula that allows us to sum an arithmetic progression. This will make the program way more efficient with bigger numbers.
sum = n(a1+an)/2
Where sum is the result, n is the inpnum, a1 is the first number of the progression and an is the place that ocuppies n (the inpnum) in the progression.
So what I have done is calculate the sum of all the numbers from 1 to inpnum and then substract the sum of all the multiples of 5 from 5 to n.
#include <iostream>
using namespace std;
int main (void)
{
int inpnum, quotient, sum;
cout << "Enter the number to print the SUM : ";
cin >> inpnum;
// Finds the amount of multiples of 5 from 5 to n
quotient = inpnum/5;
// Sum from 1 to n // Sum from 5 to n of multiples of 5
sum = (inpnum*(1+inpnum))/2 - (quotient*(5+(quotient)*5))/2;
cout << "The sum of the numbers is: " << sum;
}
thanks every one but the problem is solved . the mistake was very small. i forget to write "()" in if condition.
#include <iostream>
using namespace std;
int main()
{
int inputnumber = 0;
int sum = 0;
int count= 1;
cout<<"Enter the number to print the SUM : ";
cin>>inputnumber;
while(count<=inputnumber)
{
if ((count % 5)!=0)//here the ()..
{
sum = sum + count;
}
count = count +1;
}
cout<<"the sum of the numbers are : "<<sum;
}

reverse the position of integer digits?

i have to reverse the position of integer like this
input = 12345
output = 54321
i made this but it gives wrong output e.g 5432
#include <iostream>
using namespace std;
int main(){
int num,i=10;
cin>>num;
do{
cout<< (num%i)/ (i/10);
i *=10;
}while(num/i!=0);
return 0;
}
Here is a solution
int num = 12345;
int new_num = 0;
while(num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
Your loop terminates too early. Change
}while(num/i!=0);
to
}while((num*10)/i!=0);
to get one more iteration, and your code will work.
If you try it once as an example, you'll see your error.
Input: 12
first loop:
out: 12%10 = 2 / 1 = 2
i = 100
test: 12/100 = 0 (as an integer)
aborts one too early.
One solution could be testing
(num % i) != num
Just as one of many solutions.
Well, remember that integer division always rounds down (or is it toward zero?) in C. So what would num / i be if num < 10 and i = 10?
replace your while statement
with
while (i<10*num)
If I were doing it, I'd (probably) start by creating the new value as an int, and then print out that value. I think this should simplify the code a bit. As pseudocode, it'd look something like:
output = 0;
while (input !=0)
output *= 10
output += input % 10
input /= 10
}
print output
The other obvious possibility would be to convert to a string first, then print the string out in reverse:
std::stringstream buffer;
buffer << input;
cout << std::string(buffer.str().rbegin(), buffer.str().rend());
int _tmain(int argc, _TCHAR* argv[])
{
int x = 1234;
int out = 0;
while (x != 0)
{
int Res = x % (10 );
x /= 10;
out *= 10;
out += Res;
}
cout << out;
}
This is a coding assignment for my college course. This assignment comes just after a discussion on Operator Overloading in C++. Although it doesn't make it clear if Overloading should be used for the assignment or not.
The following code works for a two-digit number only.
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
cout << (n%10) << (n/10);
return 0;
}
int a,b,c,d=0;
cout<<"plz enter the number"<<endl;
cin>>a;
b=a;
do
{
c=a%10;
d=(d*10)+c;
a=a/10;
}
while(a!=0);
cout<<"The reverse of the number"<<d<<endl;
if(b==d)
{
cout<<"The entered number is palindom"<<endl;
}
else
{
cout<<"The entered number is not palindom"<<endl;
}
}
template <typename T>
T reverse(T n, size_t nBits = sizeof(T) * 8)
{
T reverse = 0;
auto mask = 1;
for (auto i = 0; i < nBits; ++i)
{
if (n & mask)
{
reverse |= (1 << (nBits - i - 1));
}
mask <<= 1;
}
return reverse;
}
This will reverse bits in any signed or unsigned integer (short, byte, int, long ...). You can provide additional parameter nBits to frame the bits while reversing.
i. e.
7 in 8 bit = 00000111 -> 11100000
7 in 4 bit = 0111 -> 1110
public class TestDS {
public static void main(String[] args) {
System.out.println(recursiveReverse(234));
System.out.println(recursiveReverse(234 ,0));
}
public static int reverse(int number){
int reversedNumber = 0;
int temp = 0;
while(number > 0){
//use modulus operator to strip off the last digit
temp = number%10;
//create the reversed number
reversedNumber = reversedNumber * 10 + temp;
number = number/10;
}
return reversedNumber;
}
private static int reversenumber =0;
public static int recursiveReverse(int number){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number);
}
public static int recursiveReverse(int number , int reversenumber){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number,reversenumber);
}
}
I have done this simply but this is applicable upto 5 digit numbers but hope it helps
#include<iostream>
using namespace std;
void main()
{
int a,b,c,d,e,f,g,h,i,j;
cin>>a;
b=a%10;
c=a/10;
d=c%10;
e=a/100;
f=e%10;
g=a/1000;
h=g%10;
i=a/10000;
j=i%10;
cout<<b<<d<<f<<h<<j;
}`