Recursive positive digits sum program - c

I'm facing an issue, the program almost works correctly except it gives +1 in output result. For example num input is 123 = 1+2+3=6, instead it gives 7 as output.
I can simply fix this problem by adding -1 in the printf statement, but I want to know why this is happening.
#include<stdio.h>
int Sumdigits(int num);
int Sumdigits(int num){
if(num<1){
return 1;
}
else return (num%10+Sumdigits(num/10));
}
int main(){
int num;
printf("Enter Number: ");
scanf("%d",&num);
printf("%d",Sumdigits(num));
}

The problem is that Sumdigits( 0 ) will return 1 instead of 0, which does not make sense. To fix this, change
if(num<1){
return 1;
}
to:
if(num<1){
return 0;
}
It is also worth noting that your code will not work with negative numbers. Therefore, you may want to change the function Sumdigits to the following:
int Sumdigits( int num )
{
if( num == 0 )
return 0;
if ( num < 0 )
num = -num;
return num % 10 + Sumdigits(num/10);
}

You are adding 1 in this if statement
if(num<1){
return 1;
The function should be declared and defined like
unsigned int Sumdigits( unsigned int num )
{
return num == 0 ? 0 : num % 10 + Sumdigits( num / 10 );
}
If the user is allowed to deal with negative integer values then the function can be defined the following way
unsigned int Sumdigits( int num )
{
unsigned int digit = num < 0 ? -( num % 10 ) : num % 10;
return num == 0 ? 0 : digit + Sumdigits( num / 10 );
}

if (num < 1) is only handled when the digit is zero, but then you return 1, instead, so adding one to the result. This happens always, as this is the cut'n go back case that is executed always at the deepest recursion level.
It should read:
if (num < 1)
return 0;
(if you check, the only possibility for a valid number is to be zero, as it is an integer going down from a large number until you have no more digits, when you exhaust the number, it is actually zero, so it can be more readably written:
if (num == 0)
return 0;
meaning if we are at the end, then just add zero.

Related

Print a different result than actual answer (Ciel and A-B Problem)

Input:
An input contains 2 integers A and B.
Output:
Print a wrong answer of A-B. Your answer must be a positive integer containing the same number of digits as the correct answer, and exactly one digit must differ from the correct answer. Leading zeros are not allowed. If there are multiple answers satisfying the above conditions, anyone will do.
Code:
#include <stdio.h>
int no_of_zeroes(int x);
int main()
{
int a, b;
int res1, res2;
int n1, n2;
scanf("%d",&a);
scanf("%d",&b);
res1 = a - b;
res2 = res1 + 10;
n1 = no_of_zeroes(res1);
n2 = no_of_zeroes(res2);
if(res1 < 9) printf("%d",res1 + 1);
else if(res1 == 9) printf("%d",res1-1);
else if((n1 == n2) && (res1 > 9)) printf("%d",res2);
else if((n2 > n1) && (res1>9))
{
res2 = res2 - 20;
printf("%d",res2);
}
}
int no_of_zeroes(int x)
{
int count = 0;
while(x>0)
{
x = x / 10;
count++;
}
return count;
}
Error:
What different should i do, basically else if blocks are creating trouble.
Your answer must be a positive integer containing the same number of digits as the correct answer
So the answer should be a-b. But the statement also says
exactly one digit must differ from the correct answer
Since it didn't specify the position of the digit, changing the last digit only should give us the correct answer to this problem. And so counting the number of digits of the difference is redundant.
Now the issue is - how to change the last digit? It's simple. We add 1 to the difference.
But there is a catch! If the difference is 99 and we add 1 to it, the result will be 100. Here, not only we're changing more than one digit, but also the number of digits.
And so, all we have to do is subtract 1 from the difference if the last digit of the difference is 9.
And so, the if-else block should look something like this:
int diff = a - b;
if(diff%10 == 9) {
diff--;
}
else {
diff++;
}
Here's my full code:
#include <stdio.h>
int main(void) {
int a, b;
scanf("%d%d", &a, &b);
int diff = a - b;
if(diff%10 == 9) {
diff--;
}
else {
diff++;
}
printf("%d\n", diff);
return 0;
}
On a different note, the function no_of_zeroes(int x) will return 0 if x=0. But, it should return 1 under general circumstances. And so the function should be something like this:
int no_of_digits(int x)
{
/* Adding the following line should fix the issue */
if(x==0) return 1;
int count = 0;
while(x>0)
{
x = x / 10;
count++;
}
return count;
}
I think you are making this much more complicated than needed. All you need is to check the last digit of the correct result and then change it.
For 0 and positive numbers:
last digit is 0 : add 1
last digit is 1 : add 1
...
last digit is 8 : add 1
last digit is 9 : subtract 1
For negative numbers, you simply change the sign and handle it as the positive number. This can be done because -123 has the same digits as 123.
So the code can be:
void wrongCalc(int a, int b)
{
int res = a - b; // Calculate result
if (res < 0) res = -res; // Change sign if negative
int lastDigit = res % 10; // Find last digit
if (lastDigit == 9)
{
--res; // Subtract 1
}
else
{
++res; // Add 1
}
printf("%d - %d = %d (correct result is %d)\n", a, b, res, a-b);
}
Limitations:
1) The program doesn't handle the possible integer overflow in a-b
2) The program doesn't handle the possible integer overflow in res = -res;
3) The program doesn't handle the case where the correct result is INT_MAX

my prime number checker function not working properly

So this function is just supposed to return 0 if not prime and 1 if prime. Am I seeing something wrong? for example, when I give it 39, it says it returns 1 although 39 is not a prime.
int is_prime(int number){
if (number == 2) {
return 1;
}
else{
for(loop_counter ; loop_counter < number ; loop_counter++){
if(number%loop_counter == 0){
return 0;
}
else{
return 1;
}
}
}
}
In this loop
for(loop_counter ; loop_counter < number ; loop_counter++){
there is used an undeclared variable loop_counter. If it is a global variable then it shall not be used in the function because at least it is unclear what is its value.
Also within the loop you are interrupting its iterations as soon as number%loop_counter != 0. But this does not mean that the number is prime.
And if the user will pass a negative number or zero then the function will have undefined behavior.
The function can be defined the following way
int is_prime( unsigned int n )
{
int prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
The function at first excludes all even numbers except 2 because even numbers are not prime numbers. And it also excludes the number 1 because the number 1 is not prime by the definition.
int prime = n % 2 == 0 ? n == 2 : n != 1;
So within the loop there is no sense to consider divisors that are even.
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
^^^^^^
Then within the loop there is a check whether the given odd number n is divisible by an odd divisor
prime = n % i != 0;
If n % i is equal to 0 then the variable prime gets the value 0 and the loop stops its iterations due to the condition in the loop.
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
^^^^^
that can be rewritten also like
for ( unsigned int i = 3; prime != 0 && i <= n / i; i += 2 )
^^^^^^^^^^
regarding:
for(loop_counter ; loop_counter < number ; loop_counter++){
the variable: loop_counter is not initialized (nor even declared)
Perhaps you meant:
for( int loop_counter = 0; loop_counter < number ; loop_counter++){
The following proposed code:
cleanly compiles
performs the desired functionality
is NOT the fastest/best way to check if a number is prime. Rather it is a brute force method
The OPs posted code has several problems as discussed in comments to the OPs question, so will not be repeated here.
Now, the proposed code:
int is_prime(int number)
{
for( int loop_counter = 2 ; loop_counter < number ; loop_counter++)
{
if(number%loop_counter == 0)
{
return 0;
}
}
return 1;
}

difference between "cnt += num % 2;",and, "if (num % 2) ++cnt;"

the difference between "cnt += num % 2;",and, "if (num % 2) ++cnt;"
I succeeded in counting the number of '1' in binary number.
but one line which seems to do the same thing makes different result.
global variable "cnt=0" is declared top of the code
#include<stdio.h>
int cnt=0;
//and the recursive function which counts '1' is here
int one( int num ) {
if (num < 2)
{
cnt += num;
return cnt ; //here, escape and return cnt to main.
}
else
{
one(num / 2);
cnt += num % 2; //according to the remainders cnt++ AND THIS IS THE THE QUESTION CORE
}
}
void main() {
int num;
scanf("%d", &num);
cnt=one(num); //call recursive function
printf("%d", cnt); //and here, i want to watch the [RESULT]
}//main
[RESULT]
when I use " cnt += num % 2; " prints correct answer
but another code which seems same "if (num % 2) ++cnt;" prints wrong answer.
num%2 must be 0 or 1. so it adds '1' to cnt. but second code doesn't work.
which point did i miss?
Other than lack of return in else branch, you use global var cnt in a .. not an appropriate way (those are what you missed). The following code works well:
int one(int num) {
if (num < 2) {
return num;
} else {
return (num % 2) + one(num / 2);
}
}
Hope that helps.

Value is 20,10000, error appeared

To test two 32-bit integers, m whose factorial is m! can be divisible by n. If it can, the function divides() returns 1, otherwise 0.
As the codes below, the problem is when m = 2010000, error happened. Could you please explain why?
#include <stdio.h>
long factorial(long n){
if((n == 0) || (n == 1)) return 1;
else{
return (n * factorial(n-1));
}
}
int divides (long n,long m)
{
long facN;
printf("n=%ld ",n);
facN = factorial(n);
if(m != 0){
if(facN == 1) return 0;
else{
if(facN % m == 0) return 1;
else if((facN % m) != 0)return 0;
}
}
else if(m == 0) return 0;
}
int main()
{
printf("%d", divides(2000000,1));
}
You need to compute the factorial with the modulus already taken into account. Using the following identity:
(a * b) % n = ((a % n) * (b % n)) % n
we can compute the factorial as:
m! % n = (((((1 % n) * 2) % n) * 3) % n) ...) % n
A 32-bit integer can only store factorials from 0 to 12.
1*2*3*4*5*6*7*8*9*10*11*12
479001600
1*2*3*4*5*6*7*8*9*10*11*12*13
6227020800
Given that 69! is of the order of 10^98 you are probably looking at value overflows but you might also be looking at running out of memory/stack as you will be nesting 2 million deep in your recursion.
Also your check if((facN % m) != 0) is redundant as it is called in the else to if(facN % m == 0)
If your cause is all about finding out whether if m! for an m is divisible by an n, do not calculate the factorial at all.
Rather split n to its factors, check if there are enough many of those inside the numbers ranging from 1 to m, inclusive.
For example; for m = 7 and n = 28, the process should be like the following:
n % 2 == 0 ? yes
n /= 2
2 * 1 <= m ? yes
n % 2 == 0 still? yes
n /= 2
2 * 2 <= m ? yes
n % 2 == 0 still? no
n % 3 == 0 ? no
...
n % 7 == 0 ? yes
n /= 7
7 <= m ? yes
n reached 1, return 1
Something like this. If you cannot manage to write this, then you probably shouldn't be dealing with that question yet. Still, if you want, leave a comment, I can edit my answer to include a working code.
I am adding a working example, using the logic above to display whether n is a divisor of m!, just to assure you that this thing does indeed work:
#include <stdio.h>
// this function basically compares the powers of the
// prime divisors of factee and divisor
// ... returns 1 if the powers in divisor are
// ... less than or equal to the powers in factee
// ... returns 0 otherwise
int divides( long factee, long divisor ){
int amount;
for ( int i = 2; i <= factee; i++ ){
if ( divisor % i )
continue;
amount = 0;
int copy = factee;
while ( copy ){
copy /= i;
amount += copy;
}
while ( divisor % i == 0 ){
if ( !amount )
return 0;
amount--;
divisor /= i;
}
if ( divisor == 1 )
return 1;
}
return 0;
}
int main( )
{
printf( "%d", divides( 20, 10000 ) );
getchar( );
return 0;
}
amount variable calculates the amount of i there are inside the m!. In the while loop in which it gets calculated, with the first cycle, the amount of is are added, then with the second cycle, the amount of i * is are added, and so on, until there aren't any.
For example, with m = 5 and i = 2, m / 2 is 2, which is the amount of occurrence of the factor 2 inside the 5!. Then m / 2 / 2, which is 1, is the amount of occurrence of the factor 2 * 2 == 4 inside the 5!. Then m / 2 / 2 == 0 is the count for 2 * 2 * 2 == 8, which causes the loop to end due to the 0 encounter.
Edit
I fixed something important in the code, removed the outermost while which was there for nothing, something I had put as I started and apparently forgot to remove, causing potential infinite-loops. Here I also made an improved version of the function that generally runs faster than the one above:
#include <stdio.h>
// this function basically compares the powers of the
// prime divisors of factee and divisor
// ... returns 1 if the powers in divisor are
// ... less than or equal to the powers in factee
// ... returns 0 otherwise
int divides( long factee, long divisor ){
int amount;
if ( divisor % 2 == 0 ){
amount = 0;
int copy = factee;
while ( divisor % 2 == 0 ){
if ( !amount ){
copy /= 2;
if ( !copy )
return 0;
amount += copy;
}
amount--;
divisor /= 2;
}
if ( divisor == 1 )
return 1;
}
for ( int i = 3; i <= factee; i += 2 ){
if ( divisor % i )
continue;
amount = 0;
int copy = factee;
while ( divisor % i == 0 ){
if ( !amount ){
copy /= i;
if ( !copy )
return 0;
amount += copy;
}
amount--;
divisor /= i;
}
if ( divisor == 1 )
return 1;
}
return 0;
}
int main( ) {
printf( "%d", divides( 34534564, 345673455 ) );
//printf( "%d", divides( 20, 10000 ) );
getchar( );
return 0;
}
long can support a value in the range of -2,147,483,647 to 2,147,483,647, here 2000000! is out of the range of long, that is why it is showing error.

C: Recursive function for inverting an int

I had this problem on an exam yesterday. I couldn't resolve it so you can imagine the result...
Make a recursive function: int invertint( int num) that will receive an integer and return it but inverted, example: 321 would return as 123
I wrote this:
int invertint( int num ) {
int rest = num % 10;
int div = num / 10;
if( div == 0 ) {
return( rest );
}
return( rest * 10 + invert( div ) )
}
Worked for 2 digits numbers but not for 3 digits or more. Since 321 would return 1 * 10 + 23 in the last stage.
Thanks a lot!
PS: Is there a way to understand these kind of recursion problems in a faster manner or it's up to imagination of one self?
int invertint( int num ) {
int i ;
for(i=10;num/i;i*=10);
i/=10;
if(i == 1) return num;
return( (num % 10) * i + invertint( num / 10 ) );
}
Your mistake is that in the last statement you are multiplying rest by 10. Why only 10? You need to shift the rest digit by as many digits as there are left in the remaining part of the number. You are shifting by only 1. No wonder it works only for 2-digit numbers.
The last part should be done along the lines of
int tail = invert( div );
int deg = /* number of digits in `tail` */;
return rest * (int) pow(10, deg) + div;
The problem is with return(rest * 10 + invert(div)). You can't do the multiplication yourself. The factor depends on the number of times the function is recursed, thus you have to provide the carry as a second argument to your function (carry is initialized with 0)
If you do it the other way, you won't need a counter.
int invertint(int num)
{
if (0 == num || 0 == num % 10) {
return num / 10;
}
int digits = floor(log10(num)) + 1;
int modulus = pow(10, digits - 1);
return invertint(num % modulus) * 10 + num / modulus;
}
Note that this isn't as simple as I originally thought - I had to use math.
int reverse(int no,int rev)
{
if(no!=0)
return reverse(no/10,rev*10+no%10);
else
return rev;
}
call this method as reverse(numberToReverse,0)
Just as an alternative, this could be done without recursion.
int invertint(int num)
{
int res = 0;
while (num != 0)
{
res = res * 10 + (num % 10);
num /= 10;
}
return res;
}
But since recursion was the assignment, given the int(int) signature, easiest would be with a pow(log10)) variation (provided that you're allowed to include math.h ? )
int invertint(int num)
{
if (num == 0) return 0;
return invertint(num / 10) + (int)pow(10, (int)log10(num)) * (num % 10);
}
This is the simplest approach.
int sum=0;
int reverse(int n)
{
if(n>0)
{
sum=(sum*10)+(n%10);
reverse(n/10);
}
return sum;
}

Resources