I wanna make a funcion that will take a natural number and make a new number so every digit in the old number will be incremented and if the digit is 9 it will become zero, but not to check specificly if the digit is 9.
example:
930 will return 41
9999 will return 0
879021 will return 980132.
This is what i got so far:
int newNumber(int n)
{
int dig;
if (n < 9)
return n + 1;
dig = n % 10;
dig++;
n = n / 10;
n = n * 10 + dig;
return newNumber(n/10);
}
There are a couple of issues with your code:
It doesn't handle a single digit of 9 (which cause a stack overflow).
Adding 1 to 9 makes 10 not 0.
I've run it through the sample data you supplied and it seems to work (in C#) and it has a hard core recursive line at the end.
int newNumber(int n)
{
if (n == 9)
return 0;
if (n < 9)
return n + 1;
return (newNumber(n / 10) * 10) + newNumber(n % 10);
}
Here's to avoid the check for n == 9:
int newNumber(int n)
{
static int table[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
return (n <= 9) ? table[n] : (newNumber(n / 10) * 10) + newNumber(n % 10);
}
A lookup table seems the most appropriate and does exactly what the requirements describe. Trying to use the non-compatible arithmetic operators results in side effects (as we see in Bathsheba's answer for example), that then need to be corrected.
unsigned newNumber(unsigned n, unsigned c = 0)
{
return n ? (n + 1) % 10 + 10 * newNumber(n / 10, 1 + c) : !c;
}
is one way, and it will treat 0 as 1, via the !c branch where c counts the number of recursions. Note the tail recursion in the ternary conditional branch - some compilers will optimise a tail recursion out to a simple loop, see What is tail recursion?
Bathsheba's solution posted above is very elegant by using the ternary operator, but it will give you a wrong result if the input is zero. To avoid that you may use a stub function:
#include <stdio.h>
int incDigits(int n)
{
return n ? (n + 1) % 10 + incDigits(n / 10) * 10 : 0;
}
int newNumber(int n)
{
return n ? incDigits(n) : 1;
}
int main()
{
for(int i = 0; i <= 100; ++i)
{
int n = newNumber(i);
printf("%d -> %d\n", i, n);
}
}
EDIT: user meaning-matters also posted a way to fix the input value problem using a lookup table, but he still has to check if n equals 9, which is something you don't want. So I believe using a stub function still is the best way.
Two ternary operator has been used to take care of the two cases:
i) number equal to 9
ii) number not equal to 9 => Another ternary operator is used to take care of further two possible cases:
a) number greater than 9( return sum of num(n/10)*10 and num(n%10) ); this can be further elaborated based on the argument fed to the num function.
b)number smaller than 9(return number plus one(n+1))
Once this function is called from the main function with argument equal to the number to be transformed in the manner asked in the question, each call in line4 will undergo recursion until they pass the argument to the subsequent iteration less than or equal to 9(which leads to termination of the recursion). With basic understanding of recursion, the above para can easily be understood in context to the subroutine below.
Blockquote
int num(int n)//line1
{//line2
int t;//line3
t=(n==9?0:(n>9?num(n/10)*10+num(n%10):n+1));//line4
return t;/line5
}//line6
Blockquote
Related
I tried to develop a recursive function that finds the nth term of the sequence (1,1,3,7,17,41,99,239,577,1393 ...), however, I was unsuccessful:
int progRec(int n){
return 2*progRec(n-1) + progRec(n-2);}
Any thoughts?
Add the stop condition. I assume it's 1 if n <= 2:
int progRec(int n) {
if (n <= 2) {
return 1;
}
return 2 * progRec(n - 1) + progRec(n - 2);
}
You can optimize this recursion by eliminating the second branching, which is just recalculating already visited values. Just pass the previous calculated terms as an argument:
int progRec(int n, int val = 1, int prev = 1) {
return n <= 2 ? val : progRec(n - 1, 2 * val + prev, val);
}
You can optimize it further into a for loop because now it's just a tail-recursive function.
EDIT: When I upload the code to the automatic testing platform the program doesn't crash there - it returns the correct result, but takes too long (exceeds 5 seconds)... wtf...
For university I have to implement a function that returns the number of steps taken from the input to reach 1, by following the collatz conjecture. The conjecture is very simple - given any integer number:
1. If it is even - divide it by two (n/2)
2. If it is odd - times it by 3 and add one (n*3+1)
The conjecture is that all numbers will eventually reach 1. We don't have to prove or check this, we just need to return the steps taken for a given number.
We have done this problem before, but this time we must check much larger numbers (they specify to use long instead of int) AND use recursion. They have given us skeleton code, and asked us to implement only the function - so all of my code is contained inside
int lengthCollatz(long n) { //mycode }
The skeleton code in the main collects two input values - a and b, where a < b <100000000. It checks how many steps it takes for each number between a and b, following the collatz sequence, to reach 1, and then returns the number with the highest amount of steps taken.
The function I added seems to work perfectly fine, but at larger values (when input 2 is in the millions) it seems to crash for no reason and gives no error. I've tried changing everything to unsigned longs and even long longs to see if something is overflowing - in that case the program just gets stuck... I don't understand what's wrong, please help me diagnose the error. P.S. How can I improve the speed of these calculations? We have a limit of 5 seconds.
All of my code is inside the lengthCollatz function (and the length global variable just above it) Can you identify the problem?
#include <stdio.h>
#define MAX64 9223372036854775807L /* 2ˆ63 -1 */
int length = 0;
int lengthCollatz(long n) {
length++;
//if not 1
if(n!=1){
//if odd
if(n&1) {
lengthCollatz(n=n*3+1);
}
//if even
else {
lengthCollatz(n/=2);
}
}
//if reached n = 1
else {
//return amount of steps taken
int returnLength = length;
length = 0;
return returnLength;
}
}
int main(int argc, char *argv[])
{
int n, a, b, len=-1;
scanf ("%d %d", &a, &b);
while (a <= b) {
int l = lengthCollatz(a);
if (l > len) {
n = a;
len = l;
}
a++;
}
printf("%d\n", n);
return 0;
}
Updated function:
int lengthCollatz(long n) {
if(n==1){
//return depthRecursion;
}
else {
if(n&1) {
n=n*3+1;
}
else {
n/=2;
}
return lengthCollatz(n);
}
}
Here's one alternative version which does not segfault for the input range given by OP:
int collatz(unsigned long n)
{
if (n == 1)
return 1;
else if (n & 1)
return 1 + collatz(n * 3 + 1);
else
return 1 + collatz(n >> 1);
}
AFAICT, it works OK, but it's very slow. 29 seconds on my mediocre PC. An optimized version runs two seconds faster by not calling itself when the result can be precomputed, but that version borders on manual loop unrolling. FWIW:
int collatz(unsigned long n)
{
if (n == 1)
return 1;
if (n & 1)
return 2 + collatz((n * 3 + 1) >> 1);
// Is n dividable by 16?
if (n & 0xF == 0)
return 4 + collatz(n >> 4);
// Is n dividable by 8?
if (n & 0x7 == 0)
return 3 + collatz(n >> 3);
// Is n dividable by 4?
if (n & 0x3 == 0)
return 2 + collatz(n >> 2);
return 1 + collatz(n >> 1);
}
There are of course other ways to solve this, but to finish in five seconds? Please post the solution if you find one.
I need to know if a number can be obtained by incrementing 1 by 4 iteratively. Those numbers are 5, 9, 13, 17, 21, etc. For this, I am presently doing the following:
#include <stdio.h>
int main() {
int number = 13;
int i;
for (i = n; i > 0; i -= 4) {
if (i == 1) {
printf("yes\n");
break;
}
}
if (i <= 0)
printf("no\n");
}
But this seems to be extremely inefficient O(n) approach. I would appreciate an O(1) solution for this, can I do better?
Obviously, you want to check if a number n is of the form
n = 1+4k
so you just need to check if its predecessor is evenly divisible by 4.
If you have binary 2's complement numbers, the latter is the case if the last 2 bits are 0.
Hence:
int check(int n) { return (n-1)&3 == 0; }
To get hat even shorter, a number of the form 1+4k will have the last two bits a s01:
int check(int n) { return n&3 == 1; }
You can use the modulus operator:
if ( num % 4 == 1 ) printf("yep");
Subtract 1 and make a modulo division by 4. If 0 is the result you have a match.
For our activity today, we were tasked to make using recursion with the sum of digits. I already made this program:
int main()
{
int num = 0, sum;
printf("Enter an integer: ");
scanf("%d",&num);
//counter=1;
for ( sum=0; num>0;)
{
sum = sum + num % 10;
num = num /10;
}
printf("Sum = %d", sum);
getch();
return 0;
}
Our teacher added "Input and output must be done in the main() function." Am doing the right thing? Or am I missing something in my code?
To do recursion, create a function that recurses rather than using a for loop.
int SumDigits(int i) {
if (i < 10) {
return i;
}
else {
return i%10 + SumDigits(i/10);
}
}
scanf("%d", &i);
printf("%d\n", SumDigits(i));
What you have there is an iterative solution, not a recursive one.
Recursion involves defining the problems in terms of a simpler version of the problem, all the time working towards a fixed end point.
The fixed end point in this case is any number less than 10, for which the value is that digit.
The transition to a simpler case (for numbers greater than 9) is simply to add the least significant digit to the result of the number divided by ten (integer division).
Since it's classwork, pseudo-code only I'm afraid.
def digitSum (n):
if n < 10:
return n
return (n % 10) + digitSum (n / 10)
If you follow that for the number 314, you'll see what happens.
At recursion level one, n == 314 so it calculates 314 % 10 to get 4 and calls digitSum(31).
At recursion level two, n == 31 so it calculates 31 % 10 to get 1 and calls digitSum(3).
At recursion level three, n == 3 so it just returns 3
Back up to level two, that's added to the remembered 1 and returned as 4.
Back up to level one, that's added to the remembered 4 and returned as 8.
Hence you end up with the digit sum of 8 for the number 314.
So, my basic problem is that I'm trying to write a program for a small project I'm working on for fun.
Basically, my issue is this: I need to take user input, as an int, say 15, then manipulate the number so that it returns the result of 1 + 5, being 6. Or for another example say the number is 29, will give you 2 + 9 = 11, which would then need to be reduced down again to 1 + 1 = 2. That could probably be handled easily, but I'm stuck on how to actually split the int apart without having to take the numbers in one by one. I guess it's possible to with RegEx, but I was looking for a more efficient method.
This is not a particularly good job for a regex. The usual way would be to get individual digits as the remainder after dividing by 10.
A sample code is here:
int sum_of_digits(int n)
{
if(n < 10)
{
return n;
}
int sum = 0;
while( n > 0)
{
sum += n % 10;
n /= 10;
}
return sum_of_digits(sum);
}
int main()
{
int n1 = sum_of_digits(29);
int n2 = sum_of_digits(15);
}
In C, this would do the trick for two digits:
digit_sum = my_int%10 + my_int/10
I think the quickest way here is to use / (divide) and % (modulus) operators to traverse your integer.
int base = 15;
int acum = 0;
while (base > 0) {
acum = acum + (base % 10);
base = base / 10;
};
// At this point, base = 0 and acum = 6
// if acum > 10, then assign it to base and start again.