My function works good on debug, but not im main - c

I have to make a func that do somtheing like this 123 -> 321 with recursion
When i see work of my func via debugger i see that a changed, but when i call function on main, nothing changed
This is my code
#include <stdio.h>
#include <math.h>
long int SwapNum(long int , int);
int CountRoz(long int);
int main(){
long int a = 123;
printf("%ld", a);
SwapNum(a, CountRoz(a));
printf("%ld", a);
}
int CountRoz(long int a) {
if (a / 10 == 0)
return 1;
return 1 + CountRoz(a / 10);
}
long int SwapNum(long int a, int b) {
a +=a % 10 * pow(10, 2 * b - 1);
if (b == 1) {
return 1;
}
b--;
return SwapNum(a / 10, b);
}
Can you help me, because I cant find error

You can also try passing by reference although I'm not sure your algorithm is exactly right.
long int SwapNum(long int *, int);
...
SwapNum(&a, CountRoz(a));
...
long int SwapNum(long int *a, int b) {
*a += *a % 10 * pow(10, 2 * b - 1);
if (b == 1) { return 1; }
b--;
long int a2 = *a/10;
return SwapNum(&a2, b);
}
So, the modulus operator is probably what you're trying for in your first line in Swapnum. 123 % 10 yields the remainder of 123 divided by 10.
And remember, integer math will yield integers; 12/10 yields 1.
Let's say we start with:
123, 0
123/10, 0*10 + 123%10 => 12, 3
12/10, 3*10 + 12%10 => 1, 32
1/10, 32*10 + 1%10 => 0, 321
0, 321 => no more digits left from a, so 321 is our answer
We traverse digits in A like you planned by dividing by 10 and
also build up the return value by multiplying by 10 (plus remainder)
long int SwapNum(long int, long int);
int main(){
long int a = 12388569;
printf("%ld", a);
printf("%ld", SwapNum(a,0));
}
long int SwapNum(long int a, long int b) {
if (a == 0) return b;
return SwapNum(a/10, b*10 + a%10);
}
Hope this helps!Ron.

Related

Unexpected result of trace table

I am a newborn programmer and i've been studying trace tables thus far. However, it seems i'm unable to understand this one. By what i could gather the function would return (-15) as the variable 'a' receives 25 and later the 'num', which is 10, is subtracted by the former.
Yet it seems i'm wrong by PythonTutor's calculations and i still cannot get why num is still 10 after all that C magic. Would someone be so kind to explain why is this happening?
#include <stdio.h>
int num;
int func(int a, int b);
int main() {
int first = 0, sec = 50, num2;
num = 10;
num += func(first, sec);
printf("\nnum = %d\tfirst = %d\tsec = %d", num, first, sec);
return 0;
}
int func(int a, int b) {
a = (a + b) / 2;
num -= a;
return a;
}
Would someone be so kind to explain why is this happening?
Let us take this step by step
int num;
int func(int a, int b);
int main() {
// 1) `num == 0` as it is a global variable without explicit initialization.
int first = 0, sec = 50, num2;
// 2) `num` is 10
num = 10;
// 3) Before the function call, `num` is 10
num += func(first, sec);
// 7) At the end of the function call, `num` is -15 and
// the return value of 25 is added to it due to +=.
// 8) `num` is now 10 again.
printf("\nnum = %d\tfirst = %d\tsec = %d", num, first, sec);
return 0;
}
int func(int a, int b) {
a = (a + b) / 2;
// 4) `a` is 25, `num` is 10
// 5) `num` becomes 10 - 25 --> -15
num -= a;
// 6) `a == 25` and 25 is returned
return a;
}

My recursive greatest common denominator function isn't working properly

I'm trying to create a GCD (greatest common denominator) function using recursion.
I cannot understand why it isn't working properly.
For input 10 and 50 is returning 36.
Here's my code:
int main()
{
printf("Rez=%d ", gcd(10,50));
return 0;
}
int gcd(int a, int b)
{
static int n=0;
int result=1;
n++;
if(a<=1 || b<=1)
return 1;
else
{
if(a%n==0 && b%n==0)
result=n* gcd(a/n,b/n);
else
gcd(a,b);
}
return result;
}
Using a static variable is a problem because you use it in the form n * gcd(...) and the value of n shouldn't be the same than that used by the recursion. So you should pass a parameter instead. You should also add a condition to stop when n becomes greater than the smaller term :
#include <stdio.h>
int main()
{
printf("%d\n", gcd(10, 50, 1)); //==>10
printf("%d\n", gcd(7, 35, 1)); //==>7
printf("%d\n", gcd(8, 22, 1)); //==>2
printf("%d\n", gcd(49, 5, 1)); //==>1
printf("%d\n", gcd(0, 0, 1)); //==>1
printf("%d\n", gcd(4, 2, 0)); //==>0
return 0;
}
int gcd(int a, int b, int n)
{
if (n <= 0) return 0;
if (n > (a < b ? a : b) || a<=1 || b<=1) return 1;
else if(a%n==0 && b%n==0) return n * gcd(a/n, b/n, n+1);
else return gcd(a, b, n+1);
}
the static variable is the cause for the error. In
result=n* gcd(a/n,b/n);
n is evaluated after the recursion is called. So, as your recursion stops when you call gcd( 5/5, 25/5 ) and n is incremented to 6 by that call you just have
6 * gcd( 10/1, 50/1 ) = 6 * 6 * gcd( 10/2, 50/2 ) = 6 * 6 * 6 = gcd( 5/5, 25/5 ) = 6 * 6 * 6 * 1 = 216

How do I reverse the order of the digits of an integer using recursion in C programming?

Problem statement :
Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment that could only store
integers within the 32-bit signed integer range: [ −2^31, 2^31 − 1]. For
the purpose of this problem, assume that your function returns 0 when
the reversed integer overflows.
I'm trying to implement the recursive function reverseRec(), It's working for smaller values but it's a mess for the edge cases.
int reverseRec(int x)
{
if(abs(x)<=9)
{
return x;
}
else
{
return reverseRec(x/10) + ((x%10)*(pow(10, (floor(log10(abs(x)))))));
}
}
I've implemented non recursive function which is working just fine :
int reverse(int x)
{
long long val = 0;
do{
val = val*10 + (x%10);
x /= 10;
}while(x);
return (val < INT_MIN || val > INT_MAX) ? 0 : val;
}
Here I use variable val of long long type to check the result with MAX and MIN of signed int type but the description of the problem specifically mentioned that we need to deal within the range of 32-bit integer, although somehow it got accepted but I'm just curious If there is a way to implement a recursive function using only int datatype ?
One more thing even if I consider using long long I'm failing to implement it in the recursive function reverseRec().
If there is a way to implement a recursive function using only int datatype ?
(and) returns 0 when the reversed integer overflows
Yes.
For such +/- problems, I like to fold the int values to one side and negate as needed. The folding to one side (- or +) simplifies overflow detection as only a single side needs testing
I prefer folding to the negative side as there are more negatives, than positives. (With 32-bit int, really didn't make any difference for this problem.)
As code forms the reversed value, test if the following r * 10 + least_digit may overflow before doing it.
An int only recursive solution to reverse an int. Overflow returns 0.
#include <limits.h>
#include <stdio.h>
static int reverse_recurse(int i, int r) {
if (i) {
int least_digit = i % 10;
if (r <= INT_MIN / 10 && (r < INT_MIN / 10 || least_digit < INT_MIN % 10)) {
return 1; /// Overflow indication
}
r = reverse_recurse(i / 10, r * 10 + least_digit);
}
return r;
}
// Reverse an int, overflow returns 0
int reverse_int(int i) {
// Proceed with negative values, they have more range than + side
int r = reverse_recurse(i > 0 ? -i : i, 0);
if (r > 0) {
return 0;
}
if (i > 0) {
if (r < -INT_MAX) {
return 0;
}
r = -r;
}
return r;
}
Test
int main(void) {
int t[] = {0, 1, 42, 1234567890, 1234567892, INT_MAX, INT_MIN};
for (unsigned i = 0; i < sizeof t / sizeof t[0]; i++) {
printf("%11d %11d\n", t[i], reverse_int(t[i]));
if (t[i] != INT_MIN) {
printf("%11d %11d\n", -t[i], reverse_int(-t[i]));
}
}
}
Output
0 0
0 0
1 1
-1 -1
42 24
-42 -24
1234567890 987654321
-1234567890 -987654321
1234567892 0
-1234567892 0
2147483647 0
-2147483647 0
-2147483648 0
You could add a second parameter:
int reverseRec(int x, int reversed)
{
if(x == 0)
{
return reversed;
}
else
{
return reverseRec(x/10, reversed * 10 + x%10);
}
}
And call the function passing the 0 for the second parameter. If you want negative numbers you can check the sign before and pass the absolute value to this function.
In trying to learn C programming I programed this question and get some correct results and some incorrect. I don't see the reason for the difference.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h> // requires adding link to math -lm as in: gcc b.c -lm -o q11
int ReverseInt(int startValue, int decimalPlace)
{
if(decimalPlace == 0) // if done returns value
{
return startValue;
}
int temp = startValue % 10; // gets units digit
int newStart = (startValue -temp)/10; // computes new starting value after removing one digit
int newDecimal = decimalPlace -1;
int value = temp*pow(10,decimalPlace);
return value + ReverseInt(newStart,newDecimal); // calls itself recursively until done
}
int main()
{
int x, decimalP, startValue;
printf("Input number to be reversed \n Please note number must be less than 214748364 :");
scanf("%d", &x);
if (x > 214748364)
{
printf("Input number to be reversed \n Please note number must be less than 214748364 :");
scanf("%d", &x);
}
decimalP = round(log10(x)); // computes the number of powers of 10 - 0 being units etc.
startValue = ReverseInt(x, decimalP); // calls function with number to be reversed and powers of 10
printf("\n reverse of %d is %d \n", x, startValue);
}
Output is: reverse of 1234 is 4321 but then reverse of 4321 is 12340
It's late and nothing better does not come into my mind. No float calculations. Of course, integer has to be big enough to accommodate the result. Otherwise it is an UB.
int rev(int x, int partial, int *max)
{
int result;
if(x / partial < 10 && (int)(x / partial) > -10)
{
*max = partial;
return abs(x % 10) * partial;
}
result = rev(x, partial * 10, max) + abs(((x / (int)(*max / partial)) % 10) * partial);
return result;
}
int reverse(int x)
{
int max;
return rev(x, 1, &max) * ((x < 0) ? -1 : 1);
}
int main(void){
printf("%d", reverse(-456789));
}
https://godbolt.org/z/M1eezf
unsigned rev(unsigned x, unsigned partial, unsigned *max)
{
unsigned result;
if(x / partial < 10)
{
*max = partial;
return (x % 10) * partial;
}
result = rev(x, partial * 10, max) + (x / (*max / partial) % 10) * partial;
return result;
}
unsigned reverse(unsigned x)
{
unsigned max;
return rev(x, 1, &max);
}
int main(void){
printf("%u", reverse(123456));
}
when using long long to store the result all possible integers can be reversed
long long rev(int x, long long partial, long long *max)
{
long long result;
if(x / partial < 10 && (int)(x / partial) > -10)
{
*max = partial;
return abs(x % 10) * partial;
}
result = rev(x, partial * 10, max) + abs(((x / (int)(*max / partial)) % 10) * partial);
return result;
}
long long reverse(int x)
{
long long max;
return rev(x, 1, &max) * ((x < 0) ? -1 : 1);
}
int main(void){
printf("%d reversed %lld\n", INT_MIN, reverse(INT_MIN));
printf("%d reversed %lld\n", INT_MAX, reverse(INT_MAX));
}
https://godbolt.org/z/KMfbxz
I am assuming by reversing an integer you mean turning 129 to 921 or 120 to 21.
You need an initial method to initialize your recursive function.
Your recursive function must figure out how many decimal places your integer uses. This can be found by using log base 10 with the value and then converting the result to a integer.
log10 (103) approx. 2.04 => 2
Modulus the initial value by 10 to get the ones place and store it in a variable called temp
Subtract the ones place from the initial value and store that in a variable called newStart.
divide this value by 10
Subtract one from the decimal place and store in another variable called newDecimal.
Return the ones place times 10 to the power of the decimal place and add it to the function where the initial value is newStart and the decimalPlace is newDecimal.
#include <stdio.h>
#include <math.h>
int ReverseInt(int startValue, int decimalPlace);
int main()
{
int i = -54;
int positive = i < 0? i*-1 : i;
double d = log10(positive);
int output = ReverseInt(positive,(int)d);
int correctedOutput = i < 0? output*-1 : output;
printf("%d \n",correctedOutput);
return 0;
}
int ReverseInt(int startValue, int decimalPlace)
{
if(decimalPlace == 0)
{
return startValue;
}
int temp = startValue % 10;
int newStart = (startValue -temp)/10;
int newDecimal = decimalPlace -1;
int value = temp*pow(10,decimalPlace);
return value + ReverseInt(newStart,newDecimal);
}

Reverse the output of printf function in while loop

I wrote a code for a b-adic representation of a chosen number.
#include <stdio.h>
int b_adisch (int a, int b)
{
int x, y, mod, mod1;
x = a / b;
mod1 = a % b;
printf("%i\n", mod1);
do {
y = x / b;
mod = x % b;
x = y;
printf("%i\n", mod);
} while(x != 0);
return a ;
}
int main (void)
{
int a, b;
printf("pls input a ");
scanf("%i", &a);
printf("pls input b ");
scanf("%i", &b);
b_adisch(a, b);
return 0;
}
The output order will be reversed
since the printf has to be put into the while loop and the calculation starts with the last number of the representation.
Example if a = 10 and b = 2
The output is 0101
but it should be 1010
How can I change my code to make this happen?
How can i change my code to make this happen?
2 approaches:
Compute the digits from least to most significant and save in a adequate sized buffer. This is similar to OP's approach yet saves the results of each digit's computation for later printing.
#include <assert.h>
#include <limits.h>
void b_adisch(int value, int base) {
// Let us work with simple cases first.
assert(value >= 0);
assert(base >= 2 && base <= 10);
// Adequate sized buffer
char buffer[sizeof value * CHAR_BIT + 1];
// Start at end
char *end = &buffer[sizeof buffer - 1];
*end = '\0';
do {
end--;
int digit = value%base; // Find least digit
value /= base;
*end = digit + '0'; // save the digit as text
} while (value);
printf("<%s>\n", end); // print it as a string
}
Use recursion. A more radical change; This computes and prints the output of the more significant digits first.
void b_adischR_helper(int value, int base) {
// If the value is at least 2 digits, print the most significant digits first
if (value >= base) {
b_adischR_helper(value/base, base);
}
putchar(value % base + '0'); // Print 1 digit as text
}
void b_adischR(int value, int base) {
// Let us work with simple cases first.
assert(value >= 0);
assert(base >= 2 && base <= 10);
printf("<");
b_adischR_helper(value, base);
printf(">\n");
}
Test
int main() {
b_adisch(10, 2);
b_adischR(10, 2);
b_adisch(INT_MAX, 10);
b_adischR(INT_MAX, 10);
b_adisch(INT_MAX, 2);
b_adischR(INT_MAX, 2);
}
Output
<1010>
<1010>
<2147483647>
<2147483647>
<1111111111111111111111111111111>
<1111111111111111111111111111111>
You can store the output in an array as here it is stored in "arr" and later print the output in reverse order (from end to start).
#include <stdio.h>
int arr[10000]={0};
void b_adisch (int a, int b)
{
int x, y, mod, mod1,i=0,j;
x = a / b;
mod1 = a % b;
arr[i++]=mod1;
do {
y = x / b;
mod = x % b;
x = y;
arr[i++]=mod;
} while(x != 0);
for(j=i-1;j>=0;j--)
printf("%i\n",arr[j]);
}
int main (void)
{
int a, b;
printf("pls input a ");
scanf("%i", &a);
printf("pls input b ");
scanf("%i", &b);
b_adisch(a, b);
return 0;
}

Exponentiaion program

Question is this
Nancy hates any and every string that contains the number "13". Clouseau wants to gift her a string and is looking over his options, ofcourse he would never pick a string that has "13" as a substring.
Tell Clouseau the total number of such strings s that are made of exactly N characters. The strings may contain any integer from 0-9, repeated any number of times.
Input :
The first line of input file contains a number T indicating number of test cases. The following T lines, each contain an integer N.
Output :
The output file should contain answer to each query in a new line modulo 1000000009.
Constraints :
1 T 100000 ,
0 N 1000000009
I am not getting the logic correct.
# include <stdio.h>
# define MOD 1000000009
unsigned long long mod_pow(unsigned long long num, unsigned long long pow, unsigned long long mod)
{
unsigned long long test;
unsigned long long n = num;
for(test = 1; pow; pow >>= 1) {
if (pow & 1)
test = ((test % mod) * (n % mod)) % mod;
n = ((n % mod) * (n % mod)) % mod;
}
return test;
}
int main(int argc, char* argv[])
{
long t;
unsigned long long total_no, bad_no, n;
scanf ("%ld", &t);
while (t--) {
scanf ("%lld", &n);
if (n != 1) {
total_no = (10 * (mod_pow (10, n-1, MOD))) % MOD;
bad_no = ((n - 1) * (mod_pow(10, n-2, MOD))) % MOD;
printf ("%lld\n", (((total_no - bad_no) % MOD)));
}
else
printf ("10\n");
}
return 0;
}
You can use this function:
long long int bigmod ( long long a, long long p, long long m )
{
if ( p == 0 )return 1; // If power is 0, then a ^ 0 = 1 for any value of a, And 1 Mod m=1 for any value of m, So return 1
if ( p % 2 ) // If power is odd, Split it : a ^ 5 =( a )* (a ^ 4) --> left and right child respectively.
{
return ( ( a % m ) * ( bigmod ( a, p - 1, m ) ) ) % m;
}
else //If power is even then split it equally and return the result...
{
long long c = bigmod ( a, p / 2, m );
return ( (c%m) * (c%m) ) % m;
}
}
and call this function like this:
int main(){
// take input....
//Calling...
printf("result is %lld\n",bigmod(a,p,MOD)); //
return 0;
}

Resources