I have below code which works fine.
#include<stdio.h>
int calculateSum(int);
int main() {
int num;
int result;
printf("Input number = ");
scanf("%d", &num);
result = calculateSum(num);
printf("\nResult from 1 to %d = %d", num, result);
return (0);
}
int calculateSum(int num) {
int res;
if (num == 1) {
return (1);
}
else {
res = num + calculateSum(num - 1);
}
return (res);
}
Input number = 5
Result from 1 to 5 = 15
Now I am trying to give the program 2 inputs, from and to numbers.
Example: first input = 5, second = 8 and result should be = 26 (5 + 6 + 7 + 8)
Any ideas of how to go about this? failing thus far.
int calculateSum(int fromNum, int toNum) {
int res;
if (fromNum == toNum) {
return (fromNum);
}
else {
res = fromNum + calculateSum((fromNum + 1), toNum);
}
return (res);
}
At the moment, you are hard-coding 1 as the terminating point of the recursion.
What you need is to be able to use a different value for that, and the following pseudo-code shows how to do it:
def calculateSum(number, limit):
if number <= limit:
return limit
return number + calculateSum(number - 1, limit)
For efficiency, if you break the rules and provide a limit higher than the starting number, you just get back the number. You could catch that and return zero but I'll leave that as an exercise if you're interested.
It should be relatively easy for you to turn that into real code, using your own calculateSum as a baseline.
I should mention that this is a spectacularly bad use case for recursion. In general, recursion should be used when the solution search space reduces quickly (such as a binary search halving it with each recursive level). Unless your environment does tail call optimisation, you're likely to run out of stack space fairly quickly.
Instead of stopping when you reach 1, stop when you reach from.
int calculateSum(from, to) {
if (to == from) {
return from;
} else {
return to + calculateSum(from, to-1);
}
}
change 1 to from:
int calculateSum(int from,int to) {
int res;
if (to== from) {
return (from);
}
else {
res = to+ calculateSum(from,to - 1);
}
return (res);
}
You can use ternary operator.
int calculateSum(int from, int to) {
return from == to ? from : from + calculateSum(from + 1, to);
}
Related
this is my code, I want to make a function that when it is called will generate a number between 1111 to 9999, I don't know how to continue or if I've written this right. Could someone please help me figure this function out. It suppose to be simple.
I had to edit the question in order to clarify some things. This function is needed to get 4 random digits that is understandable from the code. And the other part is that i have to make another function which is a bool. The bool needs to first of get the numbers from the function get_random_4digits and check if there contains a 0 in the number. If that is the case then the other function, lets call it unique_4digit, should disregard of that number that contained a 0 in it and check for a new one to use. I need not help with the function get_random_4digitsbecause it is correct. I need helt constructing a bool that takes get_random_4digits as an argument to check if it contains a 0. My brain can't comprehend how I first do the get_random_4digit then pass the answer to unique_4digits in order to check if the random 4 digits contains a 0 and only make it print the results that doesn't contain a 0.
So I need help with understanding how to check the random 4 digits for the integer 0 and not let it print if it has a 0, and only let the 4 random numbers print when it does not contain a 0.
the code is not suppose to get more complicated than this.
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
bool unique_4digits(answer){
if(answer == 0)
return true;
if(answer < 0)
answer = -answer;
while(answer > 0) {
if(answer % 10 == 0)
return true;
answer /= 10;
}
return false;
}
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
printf("Random answer %d\n", get_random_4digit());
Instead of testing each generated code for a disqualifying zero just generate a code without zero in it:
int generate_zero_free_code()
{
int n;
int result = 0;
for (n = 0; n < 4; n ++)
result = 10 * result + rand() % 9; // add a digit 0..8
result += 1111; // shift each digit from range 0..8 to 1..9
return result;
}
You can run the number, dividing it by 10 and checking the rest of it by 10:
int a = n // save the original value
while(a%10 != 0){
a = a / 10;
}
And then check the result:
if (a%10 != 0) printf("%d\n", n);
Edit: making it a stand alone function:
bool unique_4digits(int n)
{
while(n%10 != 0){
n = n / 10;
}
return n != 0;
}
Usage: if (unique_4digits(n)) printf("%d\n", n);
To test if the number doesn't contain any zero you can use a function that returns zero if it fails and the number if it passes the test :
bool FourDigitsWithoutZero() {
int n = get_random_4digit();
if (n % 1000 < 100 || n % 100 < 10 || n % 10 == 0) return 0;
else return n;
}
"I need not help with the function get_random_4digits because it is correct."
Actually the following does not compile,
int get_random_4digit(){
int lower = 1000, upper = 9999,answer;
answer = (rand()%(upper-lower)1)+lower;
return answer;
}
The following includes modifications that do compile, but still does not match your stated objectives::
int get_random_4digit(){
srand(clock());
int lower = 1000, upper = 9999,answer;
int range = upper-lower;
answer = lower + rand()%range;
return answer;
}
" I want to make a function that when it is called will generate a number between 1111 to 9999,"
This will do it using a helper function to test for zero:
int main(void)
{
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
printf( "Random answer %d\n", random_range(1111, 9999));
return 0;
}
Function that does work follows:
int random_range(int min, int max)
{
bool zero = true;
char buf[10] = {0};
int res = 0;
srand(clock());
while(zero)
{
res = min + rand() % (max+1 - min);
sprintf(buf, "%d", res);
zero = if_zero(buf);
}
return res;
}
bool if_zero(const char *num)
{
while(*num)
{
if(*num == '0') return true;
num++;
}
return false;
}
I'm writing an recursion method to calculate collatz conjecture for a sequence of positive integers. However, instead of stopping the calculation when the value reaches 1, I need it to stop when the value become smaller than or equal to the original value. I can't figure out what condition I should put in the if statement.
int collatz (int n) {
printf("%d%s", n, " ");
if(n > collatz(n)) { // here I would get an error saying all path leads to the method itself
return n;
}
else {
if(n % 2 == 0) {
return collatz(n / 2);
}
else {
return collatz((3 * n) + 1);
}
}
}
I used two more parameters:
startValue, to pass through the recursive calls the initial value and
notFirstTime, to check if it is the first call (and not a recursive call). In this case a value n <= startValue is allowed.
Here the code:
int collatz (int startValue, int n, int notFirstTime){
printf("%d%s ", n, " ");
if(n <= startValue && !notFirstTime)
{ // here I would get an error saying all path
//leads to the method itself
return n;
}
else
{
if ( n%2==0 )
{
collatz(startValue, n/2, 0);
}
else
{
collatz(startValue, (3*n)+1, 0);
}
}
}
int main() {
int x = 27;
int firstTime = 1;
int test = collatz(x,x, firstTime);
printf("\nLast value: %d\n", test);
return 0;
}
Please note that I removed two return statements from the recursive calls.
I've started exercising some C and found this nice exercise where I have to print a triangle via input.
for the input 6 it will print
*
**
***
****
*****
******
*****
****
***
**
*
Now, looking at it I thought, well, that's not such a hard task. So I decided to try and write it using recursion, no loops and only 2 variables.
the function should looks like this:
void PrintTriangle(int iMainNumber, int iCurrNumber)
{
//Logic goes here
}
A few hours later I realized this is a lot harder than I thought, since I need to pass enough information for the function to be able to "remember" how much triangles it should print.
So now I decided to ask you if that is even possible.
(remember, no loops, no other functions, only recursion).
EDIT:
This isn't homework, this is out of sheer curiosity. However I probably can't validate for you.
I've managed to get halfway through with this
void PrintTriangle(int iMainNumber, int iCurrNumber)
{
if (iMainNumber == 0)
{
printf("\r\n");
}
else if (iMainNumber == iCurrNumber)
{
printf("\r\n");
PrintTriangle(iMainNumber - 1, 0);
}
else
{
printf("%s", MYCHAR);
PrintTriangle(iMainNumber, iCurrNumber + 1);
}
}
I got stuck trying to create the opposite function, I believe that if I could do it, I would be able to use the fact that iMainNumber and iCurrNumber are positive or negative to navigate through the functions flow.
In other words, when the parameters are negative I would print a descending star in the length of the input minus one, and when the parameters are positive I would print the ascending star in the length of the input.
I've thought about Using a flag, but not instead of 2 integers.
Maybe if I'd add another flag and have 2 integers and a flag then I could solve it, but as I said, I tried to limit myself to 2 integers.
What I'm starting to think is that there is no way to pass the information required to print an ascending star in this method without using more than 2 integers and recursion.
But I'm still not so sure about that, hence the question.
I came up with:
void PrintTriangle(int size, int indent)
{
switch(size) {
case 0:
if (indent > 1) PrintTriangle(size, indent-1);
putchar('*');
break;
case 1:
PrintTriangle(size-1, indent+1);
putchar('\n');
break;
default:
PrintTriangle(1, indent);
PrintTriangle(size-1, indent+1);
PrintTriangle(1, indent);
break; }
}
int main()
{
PrintTriangle(6, 0);
return 0;
}
as a quick first attempt. Seems to do the job.
size is the size of the triangle to print, and indent is the number of extra stars to print before each row of the triangle. size==0 means just print indent stars and no newline (used to print the indent before the triangle)
If you want something a bit more compact, you could rewrite this as:
void PrintTriangle(int size, int indent)
{
if (size <= 0) {
if (indent > 1) PrintTriangle(size, indent-1);
putchar('*');
} else {
if (size > 1) PrintTriangle(1, indent);
PrintTriangle(size-1, indent+1);
if (size > 1) PrintTriangle(1, indent);
else putchar('\n'); }
}
Anything done with loops can be done with recursion with the same number of variables. You just have to tease out what is the state, and pass that updated state in a recursive call, instead of looping.
So let's do it iterativey, first. The input is size, the size of the triangle. Let's have two state variables, lineNumber from 1 to size*2-1 and columnNumber from 1 to size. Note that:
columnsForLine = lineNumber <= size ? lineNumber : size*2 - lineNumber
The iterative version would be like this:
int lineNumber = 1;
int columnNumber = 1;
int size = 6;
while (lineNumber <= size*2-1) {
printf("*");
int columnsForLine = lineNumber <= size ? lineNumber : size*2 - lineNumber;
if (columnNumber == columnsForLine) {
printf("\n");
columnNumber = 1;
lineNumber += 1;
}
else {
columnNumber += 1;
}
}
That does indeed work. Now how to do it recursively? Just tease out where state is being updated and do that as a recursive call:
void recstars(int size, int lineNumber, int columnNumber) {
if (!(lineNumber <= size*2 - 1)) {
return;
}
printf("*");
int columnsForLine = lineNumber <= size ? lineNumber : size*2 - lineNumber;
if (columnNumber == columnsForLine) {
printf("\n");
recstars(size, lineNumber + 1, 1);
}
else {
recstars(size, lineNumber, columnNumber + 1);
}
}
recstars(6, 1, 1);
And voila. Works for any size, e.g. 13.
Note that the code is basically the same, it's just a matter of doing the control flow differently. Also note that this is tail-recursive, meaning a smart compiler would be able to execute the recursive calls without growing the stack for each call.
Hmm if you only want to use 2 variables though, including the input, will be a bit trickier... you can always cheat and stuff all 3 integers into one integer, then unpack it & re-pack it each time. e.g.
void recstars(int state) {
int size = state / 10000;
int lineNumber = (state - size*10000) / 100;
int columnNumber = state - size*10000 - lineNumber*100;
if (!(lineNumber <= size*2 - 1)) {
return;
}
printf("*");
int columnsForLine = lineNumber <= size ? lineNumber : size*2 - lineNumber;
if (columnNumber == columnsForLine) {
printf("\n");
recstars(size*10000 + (lineNumber+1)*100 + 1);
}
else {
recstars(size*10000 + lineNumber*100 + (columnNumber+1));
}
}
recstars(6*10000 + 1*100 + 1);
Seems to work. Is that legit, you think?
Otherwise, the tricky part isn't the recursion, it's just getting the job done with only 2 ints for state. Can you do it iteratively with only 2 integers?
Using 2 parameters as OP suggested
void PrintTriangle(int iMainNumber, int iCurrNumber) {
if (iMainNumber < 0) { // Row (use negative iMainNumber)
printf("%c", '*');
PrintTriangle(iMainNumber + 1, 0);
if (iMainNumber == -1)
printf("\n");
} else if (iMainNumber > 0) {
if (iCurrNumber < iMainNumber) { // Preceding short lines
if (iCurrNumber > 1)
PrintTriangle(iMainNumber, iCurrNumber - 1);
PrintTriangle(-iCurrNumber, 0);
} else if (iCurrNumber == iMainNumber) {
PrintTriangle(iMainNumber, iCurrNumber - 1); // left
PrintTriangle(iMainNumber, iCurrNumber + 1); // Right
} else { // Subsequent short lines
if ((iCurrNumber - iMainNumber) < iMainNumber)
PrintTriangle(iMainNumber, iCurrNumber + 1);
PrintTriangle(-(iCurrNumber - iMainNumber), 0);
}
}
}
int main() {
PrintTriangle(3,3);
PrintTriangle(6,6);
return 0;
}
From what I have read, most suggestions have already pointed out to pass in any state you need.
However, you really don't need that many branching statements. Most of what you need, you can derive arithmetically. You can calculate the total number of recursions and derive the number of stars from the current recursion count. Also, by separating the portion of the initial invocation from the recursion, you can make usage much simpler.
Just saw that you do not want more than two integers. Consider the below and see if you really want to maintain that preference. If so, you can put the calculation of the total in the recursive portion. I think it would be less readable.
void _print_stars(int height, int total, int current)
{
int stars = current <= height ? current : 2 * height - current;
for (int i = 0; i < stars; i++) { printf("*"); }
printf("\n");
if (current != total)
{
_print_stars(height, total, current + 1);
}
}
void print_stars(int height)
{
int total_recursions = 2 * height - 1;
_print_stars(height, total_recursions, 1);
}
Pure recursion, no loops, calling program 'main()' passes only one parameter:
void PrintTheClms(int width, int stars) {
printf("*");
if stars < width then {
PrintTheClms(width, stars+1);
}
}
void PrintStars(int width) {
PrintTheClms(width, 1);
printf("\n");
}
void PrintTheRows(int size, int indent) {
PrintStars(indent);
if indent < size then {
PrintTheRows(size, indent+1);
PrintStars(indent);
}
}
void PrintTriangle(int size) {
if size > 0 then {
PrintTheRows(size, 1);
}
}
int main() {
PrintTriangle(6);
PrintTriangle(11);
// etc.
return 0;
}
Very simple -- no else clauses, no case constructs, no direction flag. Lots of procs and lots of calls, though.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int myatoi(const char* string) {
int i = 0;
while (*string) {
i = (i << 3) + (i<<1) + (*string -'0');
string++;
}
return i;
}
void decimal2binary(char *decimal, int *binary) {
decimal = malloc(sizeof(char) * 32);
long int dec = myatoi(decimal);
long int fraction;
long int remainder;
long int factor = 1;
long int fractionfactor = .1;
long int wholenum;
long int bin;
long int onechecker;
wholenum = (int) dec;
fraction = dec - wholenum;
while (wholenum != 0 ) {
remainder = wholenum % 2; // get remainder
bin = bin + remainder * factor; // store the binary as you get remainder
wholenum /= 2; // divide by 2
factor *= 10; // times by 10 so it goes to the next digit
}
long int binaryfrac = 0;
int i;
for (i = 0; i < 10; i++) {
fraction *= 2; // times by two first
onechecker = fraction; // onechecker is for checking if greater than one
binaryfrac += fractionfactor * onechecker; // store into binary as you go
if (onechecker == 1) {
fraction -= onechecker; // if greater than 1 subtract the 1
}
fractionfactor /= 10;
}
bin += binaryfrac;
*binary = bin;
free(decimal);
}
int main(int argc, char **argv) {
char *data;
data = malloc(sizeof(char) * 32);
int datai = 1;
if (argc != 4) {
printf("invalid number of arguments\n");
return 1;
}
if (strcmp(argv[1], "-d")) {
if (strcmp(argv[3], "-b")) {
decimal2binary(argv[2], &datai);
printf("output is : %d" , datai);
} else {
printf("invalid parameter");
}
} else {
printf("invalid parameter");
}
free(data);
return 0;
}
In this problem, myatoi works fine and the decimal2binary algorithm is correct, but every time I run the code it gives my output as 0. I do not know why. Is it a problem with pointers? I already set the address of variable data but the output still doesn't change.
./dec2bin "-d" "23" "-b"
The line:
long int fractionfactor = .1;
will set fractionfactor to 0 because the variable is defined as an integer. Try using a float or double instead.
Similarly,
long int dec = myatoi(decimal);
stores an integer value, so wholenum is unnecessary.
Instead of
i = (i << 3) + (i<<1) + (*string -'0');
the code will be much more readable as
i = i * 10 + (*string - '0');
and, with today's optimizing compilers, both versions will likely generate the same object code. In general, especially when your code isn't working, favor readability over optimization.
fraction *= 2; // times by two first
Comments like this, that simply translate code to English, are unnecessary unless you're using the language in an unusual way. You can assume the reader is familiar with the language; it's far more helpful to explain your reasoning instead.
Another coding tip: instead of writing
if (strcmp(argv[1], "-d")) {
if (strcmp(argv[3], "-b")) {
decimal2binary(argv[2], &datai);
printf("output is : %d" , datai);
} else {
printf("invalid parameter");
}
} else {
printf("invalid parameter");
}
you can refactor the nested if blocks to make them simpler and easier to understand. In general it's a good idea to check for error conditions early, to separate the error-checking from the core processing, and to explain errors as specifically as possible so the user will know how to correct them.
If you do this, it may also be easier to realize that both of the original conditions should be negated:
if (strcmp(argv[1], "-d") != 0) {
printf("Error: first parameter must be -d\n");
else if (strcmp(argv[3], "-b") != 0) {
printf("Error: third parameter must be -b\n");
} else {
decimal2binary(argv[2], &datai);
printf("Output is: %d\n" , datai);
}
void decimal2binary(char *decimal, int *binary) {
decimal = malloc(sizeof(char) * 32);
...
}
The above lines of code allocate a new block of memory to decimal, which will then no longer point to the input data. Then the line
long int dec = myatoi(decimal);
assigns the (random values in the) newly-allocated memory to dec.
So remove the line
decimal = malloc(sizeof(char) * 32);
and you will get the correct answer.
if(!strcmp(argv[3] , "-b"))
if(!strcmp(argv[3] , "-d"))
The result of the string compare function should be negated so that you can proceed. Else it will print invalid parameter. Because the strcmp returns '0' when the string is equal.
In the 'decimal2binary' function you are allocating a new memory block inside the function for the input parameter 'decimal',
decimal = malloc(sizeof(char) * 32);
This would actually overwrite your input parameter data.
UVA problem 100 - The 3n + 1 problem
I have tried all the test cases and no problems are found.
The test cases I checked:
1 10 20
100 200 125
201 210 89
900 1000 174
1000 900 174
999999 999990 259
But why I get wrong answer all the time?
here is my code:
#include "stdio.h"
unsigned long int cycle = 0, final = 0;
unsigned long int calculate(unsigned long int n)
{
if (n == 1)
{
return cycle + 1;
}
else
{
if (n % 2 == 0)
{
n = n / 2;
cycle = cycle + 1;
calculate(n);
}
else
{
n = 3 * n;
n = n + 1;
cycle = cycle+1;
calculate(n);
}
}
}
int main()
{
unsigned long int i = 0, j = 0, loop = 0;
while(scanf("%ld %ld", &i, &j) != EOF)
{
if (i > j)
{
unsigned long int t = i;
i = j;
j = t;
}
for (loop = i; loop <= j; loop++)
{
cycle = 0;
cycle = calculate(loop);
if(cycle > final)
{
final = cycle;
}
}
printf("%ld %ld %ld\n", i, j, final);
final = 0;
}
return 0;
}
The clue is that you receive i, j but it does not say that i < j for all the cases, check for that condition in your code and remember to always print in order:
<i>[space]<j>[space]<count>
If the input is "out of order" you swap the numbers even in the output, when it is clearly stated you should keep the input order.
Don't see how you're test cases actually ever worked; your recursive cases never return anything.
Here's a one liner just for reference
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
Not quite sure how your code would work as you toast "cycle" right after calculating it because 'calculate' doesn't have explicit return values for many of its cases ( you should of had compiler warnings to that effect). if you didn't do cycle= of the cycle=calculate( then it might work?
and tying it all together :-
int three_n_plus_1(int n)
{
return n == 1 ? 1 : three_n_plus_1((n % 2 == 0) ? (n/2) : (3*n+1))+1;
}
int max_int(int a, int b) { return (a > b) ? a : b; }
int min_int(int a, int b) { return (a < b) ? a : b; }
int main(int argc, char* argv[])
{
int i,j;
while(scanf("%d %d",&i, &j) == 2)
{
int value, largest_cycle = 0, last = max_int(i,j);
for(value = min_int(i,j); value <= last; value++) largest_cycle = max_int(largest_cycle, three_n_plus_1(value));
printf("%d %d %d\r\n",i, j, largest_cycle);
}
}
Part 1
This is the hailstone sequence, right? You're trying to determine the length of the hailstone sequence starting from a given N. You know, you really should take out that ugly global variable. It's trivial to calculate it recursively:
long int hailstone_sequence_length(long int n)
{
if (n == 1) {
return 1;
} else if (n % 2 == 0) {
return hailstone_sequence_length(n / 2) + 1;
} else {
return hailstone_sequence_length(3*n + 1) + 1;
}
}
Notice how the cycle variable is gone. It is unnecessary, because each call just has to add 1 to the value computed by the recursive call. The recursion bottoms out at 1, and so we count that as 1. All other recursive steps add 1 to that, and so at the end we are left with the sequence length.
Careful: this approach requires a stack depth proportional to the input n.
I dropped the use of unsigned because it's an inappropriate type for doing most math. When you subtract 1 from (unsigned long) 0, you get a large positive number that is one less than a power of two. This is not a sane behavior in most situations (but exactly the right one in a few).
Now let's discuss where you went wrong. Your original code attempts to measure the hailstone sequence length by modifying a global counter called cycle. However, the main function expects calculate to return a value: you have cycle = calculate(...).
The problem is that two of your cases do not return anything! It is undefined behavior to extract a return value from a function that didn't return anything.
The (n == 1) case does return something but it also has a bug: it fails to increment cycle; it just returns cycle + 1, leaving cycle with the original value.
Part 2
Looking at the main. Let's reformat it a little bit.
int main()
{
unsigned long int i=0,j=0,loop=0;
Change these to long. By the way %ld in scanf expects long anyway, not unsigned long.
while (scanf("%ld %ld",&i,&j) != EOF)
Be careful with scanf: it has more return values than just EOF. Scanf will return EOF if it is not able to make a conversion. If it is able to scan one number, but not the second one, it will return 1. Basically a better test here is != 2. If scanf does not return two, something went wrong with the input.
{
if(i > j)
{
unsigned long int t=i;i=j;j=t;
}
for(loop=i;loop<=j;loop++)
{
cycle=0;
cycle=calculate(loop );
if(cycle>final)
{
final=cycle;
}
}
calculate is called hailstone_sequence_length now, and so this block can just have a local variable: { long len = hailstone_sequence_length(loop); if (len > final) final = len; }
Maybe final should be called max_length?
printf("%ld %ld %ld\n",i,j,final);
final=0;
final should be a local variable in this loop since it is separately used for each test case. Then you don't have to remember to set it to 0.
}
return 0;
}