Base Case for factorial recursive solution - factorial

I've looked at many recursive solutions and I don't understand why sometimes the base case is "if(num === 0) return 1;" and other times it is "if(num === 1) return 1;" Which one is it?

you should use something along the line of
int factstart(int num){
if(num<0) return -1;
else return num * fact(num-1);
}
int fact(int num){
if(num == 0) return 1;
else return num*fact(num-1);
}
the reason that people use that people use 1 or 0 is it will get them an answer most of the time, but this isn't defensive programming, and if a negative number is given for either, then the answer will be some random value, and if 0 is given for the case that they have equal to 1 then it will give 0 even though 0 factorial is 1

Related

Why is my factorial program using recursion not working

I am new to coding. so I wanted to write a c program using recursion to calculate the factorial of a number.
#include <stdio.h>
int fact(int a) {
int n = 1;
if (a != 0)
return;
else
n = n * a;
a--;
fact(a);
return n;
}
int main() {
printf("%d", fact(5));
return 0;
}
This is the program I have written. I know this is probably wrong but I think I would understand programming better if I was able to understand why the above program is exactly wrong.
Because whenever you pass any value other than 0 to fact your code exits without even returning a value:
if(a!=0)
return;
You should get at least a warning from your compiler that this is invalid code, since fact is expected to always return an int value.
But even more so, this is a logical error.
Did you mean to write:
if (a == 0) return 1; //0! = 1
Lev M. pointed out your mistakes in his answer. This is a working recursive implementation of the factorial algorithm.
unsigned int fac(unsigned char n)
{
if (n == 0)
return 1;
return n * fac(n - 1);
}

Finding proper divisors in c

I'm trying to write a function that finds the number of divisors of a number n, which are smaller or equal to a number k using recursion (in C programming language).
For example, (9,3) should return 2 since the only positive divisors of 9 that are less than or equal to 3 are 1 and 3.
Here's what I've tried but can't figure out why it's not working:
int divisors(int n,int k){
int sum = 0;
if (k==0){
return 0;
}
else if (n%k==0){
return sum++ + divisors(n,k-1);
}
return sum;
}
If anyone is able to help I'd appreciate it.
You are almost there. I made a few fixes:
k == 1 as a break condition is faster, although k == 0 works fine.
The integer sum is useless.
When not counting, your thinking was almost correct. You should return 0 but for this specific case while keeping the function calculating the next ints (recursion). Therefore you should return 0 + divisors(n, k-1)
int divisors(int n,int k){
if (k == 1) return 1;
if (n % k == 0) return 1 + divisors(n, k-1);
return divisors(n, k-1);
}
You are not handling the resolution of the recursion properly
There is no need for a sum variable, instead you want to return the function call (or 0) in any case.
If you find a number so that n%k==0 holds true, you want to return 1 + the results of the next case. However, if you then find a number that is neither 0, nor a match it will stop, instead of checking all numbers down to 0. Therefore adjusting your code in the following way will solve the problem:
int divisors(int n,int k){
if (k==0)
return 0;
else if (n%k==0)
return divisors(n,k-1) + 1;
else
return divisors(n,k-1);
}

Factorization in C-Recursion

I've been asked to write a void function in c(no loops), that gets an even number(lets say 80), and prints it like this
2*2*5*2*2
As you can see the result is 80 lol.
Between 2 numbers you need to print "*", and the odd number(for my example,5) you need to print it in the middle, or if there is an odd numbers of "2" in the number, lets say 96 you need to print it like that:2*2*2*3*2*2
If the given number is odd, return the number.
I whould like to get not only te answer, but the way you "think" before starting to code.
Here is what i got so far
if(n%4==0)
{
printf("2*");
PrintTwos(n/4);
return;
}
if(n%2==0)
{
printf("*2");
PrintTwos(n/2);
return;
}
printf("%d",n);
here is some pseudo code:
func(nbr)
isOdd(nbr) // recursive stop condition
print nbr
return
evenNbr = findFirstEven(nbr) //return the shortest even number from nbr
print evenNbr
func(nbr / evenNbr)
I didn't add logic for the * printing because i'm sure u can figure that about by yourself. And one case will break that pseudo code, but that's a good start to help you thinking about what your recursive function should do.
EDIT following comments: (NOT COMPLETE : odd number in the middle is missing in this)
int findFirstEven(nbr, i) {
if (nbr%i != 0)
return findFirstEven(nbr, i++);
return i;
}
int primefact(int n)
{
int i=2;
i = findFirstEven(n, i);
printf("%d*", i);
if(n==i)
printf("1");
return 0;
else
primefact(n/i);
}
(not tested)
You need to distribute 2's in halves, so you need to remove two twos from the number before the recursive step – otherwise the recursive step would have to know how deep it is to keep from printing too many twos on the left side.
Of course you must verify if there actualy are two twos!
So:
void PrintTwosInNumber(unsigned n)
{
if(n % 4 == 0)
{
printf("2*");
PrintTwosInNumber(n/4);
printf("*2");
}
else if(n % 2 == 0)
{
printf("2*");
PrintTwosInNumber(n/2);
}
else
printf("%u", n);
}
You can save the last recursive step with
void PrintTwosInNumber(unsigned n)
{
if(n % 4 == 0)
{
printf("2*");
PrintTwosInNumber(n/4);
printf("*2");
}
else if(n % 2 == 0)
printf("2*%u", n/2);
else
printf("%u", n);
}
Edit:
Please note the function will fall into an infinite recursion for n==0 – zero is infinitely divisible by 2. However, zero can not be represented as a product of any number of 2's and some odd numer, so it is out of scope of this problem.
Anyway if it was a real programming task, one should take that special case into account and add a protecting if(n==0) return; branch, just to be on the safe side if a caller passes a wrong parameter value.

checking for co-prime in C prgramming language

#include <stdio.h>
int iscoprime(int num1, int num2);
int main() {
int x;
x = iscoprime( 7, 8 );
printf("%d",x);a
}
int iscoprime(int num1, int num2) {
int r = 0;
int gcd = 0;
int i;
for(i = 0; (i < num1) || (i < num2) ; ++i) {
if( (num1 % i == 0) && (num2 % i == 0)) {
gcd = i;
}
}
if ( gcd == 1 ) r = 1;
return r;
}
Error: this program has stopped..??? :(
Your program has some flaws.
1) The for loop starts with i value 0. So, in the first iteration itself, floating point exception will occur. It should start from 1.
2) Your question stated that the program is finding the gcd. Which doesn't seem to be the matter. It seems to me that it is finding whether the given numbers are co-prime or not.
If its a GCD program, the return statement should be
return gcd; //without the previous if condition
Its unclear what you want your return value to mean from the iscoprime function. It looks like it returns the greatest common divisor and then checks if it is 1, then the two inputs are co-prime, and else it uses r's initial value of 0 hence meaning it will print 1 if the numbers are co-prime and 0 if they are not. Your for loop doesn't quite make sense. The max greatest common divisor of two numbers can have would be the lower of the two values. I would start your for loop at this value, 7 in your case and decrement i with each iteration and return i when both numbers divide by i without a remainder. This would would then be your greatest common divisor, if it is 1, then your two numbers are co-prime.
While this implementation is fine for small numbers, if the numbers are going to be very large, I would have a look at https://en.wikipedia.org/wiki/Euclidean_algorithm which can compute the GCD very fast and the same will still apply, if the GCD is 1, the two inputs are co-prime.

Find smallest number Q whose product of digits is N

In the following code
#include <stdio.h>
#define MAX 1000000000
int main()
{
int n,temp,prod,i;
scanf("%d",&n);
for(i=1;i<MAX;i++)
{
temp=i;
prod=1;
while(temp!=0)
{
prod=prod*(temp%10);
temp=temp/10;
}
if(prod==n)
{
printf("%d",i);
break;
}
}
return 0;
}
The code is working. I need to input a number N and find the smallest integer Q such that the product of its digits is N. For example, if N=10, Q=25. I need to output -1 if there is no such number Q. Putting the following strip of code after the if code strip gives -1 for all inputs
else
{
printf("-1");
break;
}
What am I doing wrong?
If you put the else block inside the loop then it will fire as soon as any single guess fails. You want it to fire after all guesses have failed. That means the -1 printout needs to be outside of the loop, after you've tried all the numbers and found all of them to be wrong.
But that means you can't use an else block. You'll need to use something else. How do you detect if the loop failed? One common way is to use a variable to track whether the loop succeeded or failed. For example, set found = 0 before the loop starts, and inside the if statement when you've found a match set found = 1. Then after the loop ends, check the value of found. If it's still 0 then you didn't find a match and can output -1.
int found = 0;
for (i = 1; i < MAX; i++)
{
// ...
if (prod == n)
{
printf("%d\n", i);
found = 1;
break;
}
}
if (found == 0) // could also be written: if (!found)
{
printf("-1\n");
}
What happens when i == 1? You calculate prod = 1. And unless n = 1, the if-condition is false, and you print -1 and exit the loop.
Nice problem though. How would you go about finding the solution if n = 1,000,000,000?
Better would be to find one-digit factors of N and see which combination of products is minimum.

Resources