I need to create a recursive function that counts the 2 and 6 from the number a user inputs.
For example if the user enters 26827 the count is 3.
It works with certain numbers and certain numbers it doesn't. Can someone please modify my function making sure its recursive and using very basic C++ language as I have used. Thank you! (I believe something is wrong with return type.)
int count(int n) {
static int count = 0;
if (n == 2 || n == 6) count++;
if ((n % 10 == 2) || (n % 10 == 6)) {
count++;
count(num / 10);
}
else return count;
}
One liner for fun.
int f(int n) {
return n == 0 ? 0 : (n%10==2 || n%10==6) + f(n/10);
}
int count(int n) {
if(n <= 0) return 0; // Base Condition
int countDig = 0; // Initalizing Count of digits
if(n % 10 == 2 || n % 10 == 6) // Checking whether the LSB is 2 or 6
countDig ++; // If it is then incrementing the countDig
countDig += count(n / 10); // Calling the recurive function by sending the number except its LSB
//And incrementing counter according to it
return countDig; // Returning the final count
}
you don't need to have a static value counter. It can be easily done as above. Please refer to comments given. Second the error in your code is you only calling the recursion if the LSB is 2 or 6. The recursion should be put outside the if condition in your code. Why are you using num variable. I think it should be n
You don't need statics
This should work (note return c + count(n / 10) line. That's the main recursion here)
int count(int n)
{
int c = 0;
if(n % 10 == 2 || n % 10 == 6)
c = 1;
if(n < 10)
return c;
return c + count(n / 10);
}
If you want to make it with recursion , another procedure you can apply using string manipulation.
PseudoCode:
Function ( int n):
1. Make n as a string. ( Convert Number to string)
2. Collect the first character (char C) of the string and remove the character from the string.
3. Make the main string again as a number n. ( Convert String to Number).
4. Check the character C , which is number 2 or 6 or not, count it with a flag.
5. Enter base case for which the recursion will stop.
6. return the number n , inside the Function (n) for recursion.
Related
So for the following code I am trying to reduce the amount of time the function call itself so that it is more efficient. The purpose of the code is to perform exponentiation using recursion.
int expo(const int m, const unsigned int n)
{
funcCallCounter++; //counts how many times the function is called
if (n == 0)//base case
{
return 1;
}
else if (n % 2 == 0)// for even numbers
return expo(m*m, n / 2);
else
return m * expo(m, n - 1);//for odd numbers
}
Well this is my favourite approach for the recursive expo which will always give less calls than your approach
int expo(int a, int n) {
funcCallCounter++;
if (n == 0) {
return 1;
}
int r = expo(a, n / 2);
if (n % 2 == 0) {
//Even n
return r * r;
}
else {
// Odd n
return a *r*r;
}
}
You could use shifts to make your execution faster.
n % 2 can be replaced with n & 0x01
n / 2^k can be replaced with n >> k
A division is about 20 cycles while a shift is only 1-2 cycles.
However, maybe the compiler see taht by itself and make this optimisation already.
Best
I need to create a recursive function which replaces all odd digits to a 4.
Example
User enters: 2391
Output: 2444
Please use beginner C++ language, no array and etc. Using basic C++ language and recursive would be truly helpful thanks.
int oddToFour(int num) {
int digit = num % 10;
if (digit / 2 != 0) return 4;
else return digit;
oddToFour(num/10);
}
The following code should work:
int oddToFour(int num) {
if (num == 0)
return 0;
int digit = num % 10;
if (digit % 2 == 1)
digit = 4;
return oddToFour(num/10) * 10 + digit;
}
Hope you find it helpful.
I am using a Constructor to take an unsigned int as an argument, break it into digits and assign the appropriate true and false values to a vector object. But the problem is that, my poor logic assigns the values in reverse order as the last digit is separated first and so on. The Code I have written is:
vector<bool> _bits;
uBinary(unsigned int num){
int i = 1;
while(num > 0)
{
int d = num%10;
num /= 10;
_bits.resize(i++);
if(d == 1)
{
_bits[_bits.size() - 1] = true;
}
else if(d==0)
{
_bits[_bits.size() - 1] = false;
}
}
}
For example: if argument 10011 is passed to the function uBinary() the vector object will be assigned the values in this order 11001 or true,true,false,false,true which is reversed.
All I need to do here is that, I want to assign the values without reversing the order and I don't want to use another loop for this purpose.
One way is to start at the highest possible digit (unsigned int can only hold values up to 4294967295 on most platforms) and ignore leading zeros until the first actual digit is found:
for (uint32_t divisor = 1000000000; divisor != 0; divisor /= 10) {
uint32_t digit = num / divisor % 10;
if (digit == 0 && _bits.size() == 0 && divisor != 1)
continue; // ignore leading zeros
_bits.push_back(digit == 1);
}
But finding the digits in reverse and then simply reversing them is much simpler (and at least as efficient):
do {
_bits.push_back(num % 10 == 1);
num /= 10;
} while (num != 0);
std::reverse(_bits.begin(), _bits.end());
One way you can do the reversing with another loop or std::reverse is to use recursion. With recursion you can walk down the int until you hit the last digit and then you add the values to the vector as the calls return. That would look like
void uBinary(unsigned int num)
{
if (num == 0)
return;
uBinary(num / 10);
_bits.push_back(num % 10 ? true : false);
}
Which you can see working with
int main()
{
uBinary(10110);
for (auto e : _bits)
std::cout << e << " ";
}
Live Example
Do note that it is advisable not to use leading underscores in variables names. Some names are reserved for the implementation and if you use one it is undefined behavior. For a full explanation of underscores in names see: What are the rules about using an underscore in a C++ identifier?
I have a variable which contains this numbers
int n = 6396339;
I need to determine how many digits 3 is in variable.
So far i trued like this:
int n = 6396339, counter = 0;
while (n > 0)
{
if ((n % 10) % 3 == 0) {
counter++;
}
n /= 10;
}
cout << counter << endl;
But this algorithm is not working correctly. Could you please help me to solve problem.
(n % 10) % 3 == 0
is true for any digit that is divisible by three, i.e. 0, 3, 6 and 9. Just check whether the digit is equal to 3:
(n % 10) == 3
You could print the number to a string, then traverse the string and check each character whether it is '3'.
Write a recursive function to check how many digits in the number can be divided by the digit which is after them. Example: 84963 should return 2, because 8 can be divided by 4 and 6 can be divided by 3. My function doesnt seem to output anything at all.
#include <iostream>
using namespace std;
int fun (int n);
int main()
{
int n;
cin >> n;
cout << fun(n) << endl;
return 0;
}
int fun(int n){
int count = 0;
if (fun(n % 100) % fun(n % 10) == 0)
count++;
return count;
}
Your recursion does not make much sense at the moment. A more logical approach to this would be to see if the last number (so 1 in 321), can currently divide the second last number (so 2 in 321). You could do this by defining a function that checks if that is possible, and recursively passes on the number divided by 10. That function would look something like this:
int fun(int n)
{
if (n < 10)
return 0;
int last = n % 10;
n = n / 10;
int secondlast = n % 10;
if (secondlast != 0 && last != 0 && secondlast % last == 0)
return 1 + fun(n);
else
return fun(n);
}
Update note: After looking into Vlad from moscow's comment, I moved the last != 0 part of the condition forward, to solve a bug (divide by 0).
The problem Vlad from moscow was talking about is the following: If you want, for example, the part 04 to count as 0, you should use the code as it is above. Otherwise you should remove the secondlast != 0 part.
int countIfDiv(int num) {
int pair = num % 100;
int first = pair / 10;
if (first == 0) return 0;
int second = pair % 10;
int next = num / 10;
return first % second == 0 ? 1 + countIfDiv(next) : 0 + countIfDiv(next);
}
Just pull a pair, try the division, then chop the last number and repeat.
You're not actually updating n value so you get into an infinite loop, on the other hand, your function is, initially, only designed for 3 digits number. I think that it should be something similar to:
int fun(int n, int ant, int count){
if( n == 0 )
return count;
if (ant != 0 &&
(n%10) % ant == 0)
count++;
return fun(n/10, n%10, count);
}
I should work with different number of digits.
The valid code will be
size_t fun( int n )
{
const int base = 10;
int digit = n % base;
n /= base;
return ( n == 0 ?
0 :
( digit && n % base && !( n % base % digit ) ) + fun( n ) );
}