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.
Related
I need to build a program, that would write all numbers from 0 to 100, but will place an * instead of any number that contains the digit 3 or can be divided by 3. This is what I have so far. How can I make it work?
#include <stdio.h>
main() {
int i, c;
c = 100;
for (i = 0; i <= c; i++) {
if (i % 3 == 0) {
printf("*");
}
if (i)
printf("%d\n", i);
}
}
place an * instead of any number that contains the digit 3 or can be divided by 3.
OP's code took care of the "can be divided by 3" with i % 3 == 0.
How about a little divide and conquer for the "contains the digit 3"? Put a function in there.
if (contains_the_digit(i, 3) || (i % 3 == 0)) {
printf("*\n");
} else {
printf("%d\n", i);
}
Now what is left is to define contains_the_digit(int i, int digit)
Mathematically (nice and efficient):
bool contains_the_digit_via_math(int i, int digit) {
do {
if (abs(i % 10) == digit) { // Look at the least digit, abs() to handle negative `i`
return true;
}
i /= 10; // Now look at the upper decimal digits
} while (i);
return false;
}
Or textually:
bool contains_the_digit_via_string(int i, int digit) {
char buf[30]; // Something certainly big enough
sprintf(buf, "%d", i);
return strchr(buf, digit + '0') != NULL;
}
Or use your imagination for other ideas.
The key is to take your problems and reduce them to smaller ones with helper functions: divide and conquer.
Concert the number to a string
Replace '3' with '*' within that string
i.e.
int to_be_converted =12345612343242432; // Or summat else
char num[100]; // Should be more than enough
sprintf(num, "%d", to_be_converted);
for (int i =0; num[i]; i++) {
if (num[i] -- '3') num[i] = '*';
}
printf("Here you go %s", num);
That should do the trick
Just ad the bit to go through the numbers and check if divisible by 3. I leave that to the reader.
Seeing you forgot to add the return type int to your int main(), I think this is a good time to learn to write your own function!
In this case, you want a function that can check whether the last digit of a number is a 3 when you represent that number as base-10. That's easy! The function should look like (you need to #include <stdbool.h> at the beginning of your file, too):
bool ends_in_decimal_3(int number) {
// figure out a way to find the difference
// between number, rounded to multiples of 10
// and the original number. If that difference==3,
// then this ends in 3 and you can `return true;`
}
Armed with that function, you can see whether your i itself ends in 3, or whether i/10 ends in 3 and so on. Remembering that division / in C between ints always rounds down is a good trick to do that, and also an important hint on how to implement your rounding in ends_in_decimal_3.
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);
}
So, first of all I'm a total beginner in C, we're studying it at University on the course 'Structured Programming'.
Now, the last few lectures about 'Recursive functions' have been a pain for me as a beginner. Could anyone of you be kind enough to explain me this:
So I have this little script, a recursive function that takes a decimal number and converts it to a binary one:
#include <stdio.h>
void binary(int num)
{
if (num == 0) return;
binary(num / 2);
printf("%d", num % 2);
}
int main()
{
int n;
scanf("%d", &n);
binary(n);
return 0;
}
Now I was wondering, how does this function work? I know the logic behind it and whats its supposed to do, but I don't know how it does IT. The printf in the bottom is especially throwing me off, for example if the printf function is before the recursive call, for the input decimal 10 it prints out (0101) but if its under it it prints out the correct binary number (1010)?
Any kind of help is greatly appreciated, kind regards.
The reversal is done using the call stack of the functions. By that I mean that the way the functions are called, this guarantess that the MSB will be printed first then the next one and so on.
void binary(int num)
{
if (num == 0) return;
binary(num / 2); // Wait, I will print but you first print the MSB's.
printf("%d", num % 2); // Now I print the last digit.
}
Downward motion moves the calls.
{binary(12)
{binary(6)
{binary(3)
{binary(1)
binary(0) -- returns
Now we print 1
}
print 1
}
prints 0
}
prints 0
}
If one wants to print recursively the bits of a char with leading zeros,
he may use following code:
#include <stdio.h>
void print_bit_iter(char x, int n)
{
int bit = (x & (1 << n - 1)) != 0;
printf("%d", bit);
if(n != 0)
print_bit_iter(x, n - 1);
}
int main()
{
print_bit_iter('U', 8);
}
This will have
01010101
as the output.
So, first of all I'm a total beginner in C, we're studying it at University on the course 'Structured Programming'.
Now, the last few lectures about 'Recursive functions' have been a pain for me as a beginner. Could anyone of you be kind enough to explain me this:
So I have this little script, a recursive function that takes a decimal number and converts it to a binary one:
#include <stdio.h>
void binary(int num)
{
if (num == 0) return;
binary(num / 2);
printf("%d", num % 2);
}
int main()
{
int n;
scanf("%d", &n);
binary(n);
return 0;
}
Now I was wondering, how does this function work? I know the logic behind it and whats its supposed to do, but I don't know how it does IT. The printf in the bottom is especially throwing me off, for example if the printf function is before the recursive call, for the input decimal 10 it prints out (0101) but if its under it it prints out the correct binary number (1010)?
Any kind of help is greatly appreciated, kind regards.
The reversal is done using the call stack of the functions. By that I mean that the way the functions are called, this guarantess that the MSB will be printed first then the next one and so on.
void binary(int num)
{
if (num == 0) return;
binary(num / 2); // Wait, I will print but you first print the MSB's.
printf("%d", num % 2); // Now I print the last digit.
}
Downward motion moves the calls.
{binary(12)
{binary(6)
{binary(3)
{binary(1)
binary(0) -- returns
Now we print 1
}
print 1
}
prints 0
}
prints 0
}
If one wants to print recursively the bits of a char with leading zeros,
he may use following code:
#include <stdio.h>
void print_bit_iter(char x, int n)
{
int bit = (x & (1 << n - 1)) != 0;
printf("%d", bit);
if(n != 0)
print_bit_iter(x, n - 1);
}
int main()
{
print_bit_iter('U', 8);
}
This will have
01010101
as the output.
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.