Suppose input no is f(354683257) returns 2.
It sounds like you can break this into two easier problems.
How do you find the last digit of a given number?
How do you strip off the last digit of a given number?
Here's my solution. However, what are you supposed to do if there are no even digits in the number?
int findLastEvenDigit(int n)
{
lastDigit = n % 10;
if (lastDigit % 2 == 0) return lastDigit;
else return findLastEvenDigit(n/10);
}
Assumptions: No negative numbers (not sure/relevant if it will work for them)
Related
I am learning recursion in my current class and the idea is a little tricky for me. From my understanding, when we build a function it will run as many times until our "base case" is satisfied. What I am wondering is how this looks and is returned on the stack. For an example I wrote the following function for a simple program to count how many times a digit shows up in an integer.
What does this look and work in a stack frame view? I don't completely understand how the returning works. I appreciate the help!
int count_digits(int n, int digit) {
// Base case: When n is a single digit.
if (n / 10 == 0) {
// Check if n is the same as the digit.
// When recursion hits the base case it will end the recursion.
if (n == digit) {
return 1;
} else {
return 0;
}
} else {
if (n % 10 == digit) {
return (1 + count_digits(n / 10, digit));
} else {
return (count_digits(n / 10, digit));
}
}
}
What does this look and work in a stack frame view? I don't completely understand how the returning works. I appreciate the help!
Let's try to build the solution bottom-up.
If you called the function - int count_digits(int n, int digit) as count_digits(4, 4) what would happen ?
This is the base case of your solution so it is very easy to see what is the return value. Your function would return 1.
Now, let's add one more digit and call the function like- count_digits(42, 4). What would happen ?
Your function will check the last digit which is 2 and compare with 4 since they are not equal so it will call the function count_digits(4, 4) and whatever is the returned value, will be returned as the result of count_digits(42, 4).
Now, let's add one more digit and call the function like - count_digits(424, 4). What would happen ?
Your function will check the last digit which is 4 and compare with 4 since they are equal so it will call the function count_digits(42, 4) and whatever is the returned value, will be returned by adding 1 to it. Since, number of 4s in 424 is 1 + number of 4s in 42. The result of count_digits(42,4) will be calculated exactly like it was done previously.
The recursive function builds up the solution in a top-down manner. If there are n digits initially, then your answer is (0 or 1 depending on the last digit) + answer with n-1 digits. And this process repeats recursively. So, your recursive code, reduces the problems by one digit at a time and it depends on the result of the immediate sub-problem.
You can use the C++ tutor at pythontutor.com website for step by step visualization of the stack frame. http://pythontutor.com/cpp.html#mode=edit
You can also try with smaller inputs and add some debug output to help you track and see how recursion works.
Check this stackoverflow answer for understanding what a stack frame is - Explain the concept of a stack frame in a nutshell
Check this stackoverflow answer for understanding recursion -
Understanding recursion
If you would like more help, please let me know in comments.
I got a really interesting question at a company, and I can't seem to find an answer at all.
#include <cstdio>
int main()
{
int num = 123456789;
int res = 0;
for (int i = 0; i<111111111; i++)
{
res=(res+num)%1000000000;
}
printf("06 %09d", res);
return 0;
}
I should declare num so the output is my mobile number, 305089171.
Any idea how to do that?
So to solve the problem we begin with units digit.
We need 1 at units digit so make num = 1.
Now we have res as 111111111.
Now we need 7 at tens digits. So we make num = (7 - 1(tens digit in step 2)) 1 = 61. (Also note that multiplying digit at tens place will only affect digts to left of it).
Now we have res as 777777771.
Now we need 1 at hundreds place. So if we make num = 461 (since 7+4 = 1)
and so on.
The mathematical reasoning I could think of is when you multiply a number by 111111111, digits at say tens place will only affect digits to left of it and not the digits to right of it.
Here is the value you need to put in num:
254197461
I got it by adding additional numbers one by one to num, i let you check what happens yourself.
I have no mathemacital explaination to that, but try putting numbers one by one into num and you may understand:.
1 / 61 / 461 / 7461...
The keypad is broken so the input numbers 1, 4, and 7 aren't working. In turn the computer outputs the next lowest and next highest number where 1, 4, and 7 are none of the digits.
My goal is to check out the digits and output true using a boolean function and then output the next highest number and next lowest number. I'm pretty sure I did most of what I need to do, but it isn't working out.
I have inputted the number 444, and the results that came out were 443, and 445.
Thank you for your help.
#include <iostream>
#include <conio.h>
#include <cmath>
using namespace std;
bool containDigit(int number, int digit);
int main()
{
int number, digit, lowNum, highNum;
cout<<"Enter a number between 1 and 999 for the oven temperature: ";
cin>>number;
//1st digit
digit = number / 100;
containDigit(number, digit);
if (containDigit(number, digit) == true)
{
number = number - 100;
}
//2nd digit
digit = (number / 10) % 10;
containDigit(number, digit);
if (containDigit(number, digit) == true)
{
number = number - 10;
}
//3rd Digit
digit = number % 10;
containDigit(number, digit);
if (containDigit(number, digit) == true)
{
number = number - 1;
}
cout<<number<<endl;
getche();
return 0;
}
bool containDigit(int number, int digit)
{
if ((digit == 1) || (digit == 4) || (digit == 7))
{
return true;
}
else
{
return 0;
}
}
The bug is in containDigit function. Try this:
bool containDigit(int number, int digit) {
if(digit == 1 || digit == 4 || digit == 7) return true;
return false;
}
You must use == instead of =.
Also you actually don't need number argument there.
Also there can be done several optimizations. Please look at it yourself (it's your homework) and think about repeated code.
Since this looks like homework, I will refrain from doing it for you and give you these hints:
It looks like you're not really clear on what "1st digit" is. Is it the first one from the left (hundreds) or the right (ones)? Look at your code and tell yourself how each portion of it would answer my question.
Is it ever possible for lowNum or highNum to have more than one digit different than number with your code as it is? How? Where are lowNum and highNum changed, and how?
Also, to expand on what #Al Kepp has said: When you have a function like that, try to test it with some very simple inputs rather than straight out assuming it works. This is called (or is similar to) "unit testing", which dictates that you divide your program into simple, independent units and test them separately. A simple call like containDigit(999, 4) returning true would've rang warning bells.
And speaking of warnings, always, always compile with as many of them as you can stand. (e.g. -Wall for gcc) Doing such might've warned you of the fact that you're not using the parameter number inside containDigit at all.
Your function containDigit has two problems:
It shouldn't need to receive the variable "number" as it doesn't use it
You want to compare with == not =
this works for me but I don't understand how it works at all. Could anyone explain?
for(int round = 0; round < rounds_count; round++)
{
for(int match = 0; match < matches_per_round; match++)
{
int home = (round + match) % (teams_count - 1);
int away = (teams_count - 1 - match + round) % (teams_count - 1);
if(match == 0)
away = teams_count - 1;
matches.push_back(Match(&teams[home], &teams[away], round));
}
}
What's the trick with modulo?
I'm not sure why this would be using teams_count-1 instead of teams_count, but in general, the modulus is making it "wrap around" so that if round+match is greater than the last team number, it will wrap back ground to one of the first teams instead of going past the last team.
The way away is handled, is a bit special. The % operator doesn't wrap around the way you want when you have negative numbers. For example -1 % 5 gives you -1 instead of 4. A trick to get around this problem is to add your divisor. (-1+5)%5 gives you 4.
Let's rework the code a little to make it clearer. First I'll use another variable n to represent the number of teams (again I'm not sure why teams_count-1 is used for this in your code):
int n = teams_count-1;
int home = (round + match) % n;
int away = (n - match + round) % n;
Then I'll reorganize the away calculation a little:
int n = teams_count-1;
int home = (round + match) % n;
int away = (round - match + n) % n;
It should now be clearer that the home team is starting with the current round and then adding the match, while the away team is starting with the current round and subtracting the match. The % n makes it wrap around, and the + n for away makes it wrap around properly with negative numbers
i have written a c++ code for generating first and last k digits of a number as large as 10^9. (k<=9).
cin>>n>>k;
cout << (unsigned long)floor(pow(10.0, modf(n*log10((double)n), &dummy) + k - 1)) << " "; // code that prints the first k digits
long long int ans = foo(n,k); // function that prints the last k digits
if(ans==0)
{
for(int i=0;i<k;i++) cout << "0";
}
else{
stringstream ss;
string s;
ss<<ans;
ss>>s;
if(s.size()!=k)
{
for(int i=0;i<(k-s.size());i++)
s="0"+s;
}
cout<<s;
}
where function foo() is:
long long int foo(int n, int k) // code of the function
{
long long int m=1;
for(; k > 0; k--) m*=10;
long long int r=1, t=n % m;
while(n)
{
if (n % 2)
r = r * t % m;
t = t * t % m;
n >>= 1;
}
return r;
}
this gives me output as:
if given 9 and 3 as inputs, it gives first and last 3 digits of 9 to the power 9 (9^9) i.e. 387 and 489. But I m still missing out some test cases.
Can anyone please help me finding out the test case for which my code wouldn't work ?
1 ≤ n ≤ 109, 1 ≤ k ≤ 9
the problem statement: http://www.codechef.com/problems/MARCHA4/
If n^n <= 10^9, in which case your code seems to work fine. However, if you allow bigger n, say 11^11, and ask for the last 4 digits of that, which are 0611, your code will only print 611. Basically, it doesn't print any leading zeroes when it should.
This doesn't really answer the question, and its almost trivially easy, but I figure it might be worth sharing. If there were a "long comment" capability I'd be using it.
EDIT: just noticed using str instead of repr will eliminate the L on its own
def firstAndLastDig(k, num):
s = str(num)
return (s[:k], s[-k:])
def firstAndLastDigSelfExp(k,n):
return firstAndLastDig(k,n**n)
Overflow is not an issue (the only thing is dealing with the L if you use repr instead of str),
firstAndLastDigSelfExp(6,12)
('891610', '448256')
firstAndLastDigSelfExp(42,491)
('209417336844579728122309696211520194012462', '160453713040914743773217804810667483135091')
And neither are leading zeroes
>>> firstAndLastDigSelfExp(4,9)
('3874', '0489')
This isn't do say the modular logs and stuff aren't cool - on the contrary I really liked reading about how you did this without generating the entire number. I didn't know about modf at all until reading OP's question and the body of foo is very interesting.
I think the problem is using floating point. Finding the first digit of a number actually requires perfect precision.
Unfortunately, the contest judge evidently doesn't understand that "number of significant digits" != "number of correct digits".
Perhaps there is some clever way to exactly compute (n*n, n = 10*9) without exhausting memory, but finding the first digits of a very good estimate is simply not the same as finding the first digits of the answer.
Assume that k = 9. Now, m = 1e9, and t <= 1e9 - 1.
t * t then may be as high as 1e18 - 2e9 + 1, which needs ... 59.8 bits.
Ok, not a problem with a 64-bit long long int, which has 63 bits of magnitude (and 1 of sign), but I'll leave this here so others don't repeat the same analysis.
Are you told that n is a positive integer? For example, (-8)^(-8) is perfectly well expressible in decimal but your program can't handle it.