1

How to create a c code that receive int parameter n and return the value of this mathematical equation

f(n) = 3 * f(n - 1) + 4,        where f(0) = 1

each time the program receive n , the program should start from the 0 to n which means in code (for loop) .

the problem here that i can't translate this into code , I'm stuck at the f(n-1) part , how can i make this work in c ?

Note. this code should be build only in basic C (no more the loops , no functions , in the void main etc) .

rcgldr
  • 27,407
  • 3
  • 36
  • 61
aaa
  • 23
  • 7
  • Have a look at recursion. That may be enough to unblock you, but if you want more help please show us what you've done so far. – alexroussos Jun 07 '15 at 17:05
  • The equation is recursive, but you have mentioned the use of a "for loop"; are you required to implement it using a for loop? That would suggest the point of the exercise is converting a recursive algorithm to an iterative one, since the recursive implementation does not require a loop. – Clifford Jun 07 '15 at 17:25

3 Answers3

5

It's called recursion, and you have a base case where f(0) == 1, so just check if (n == 0) and return 1 or recurse

int f(int n)
 {
    if (n == 0)
        return 1;
    return 3 * f(n - 1) + 4;
 }

An iterative solution is quite simple too, for example if f(5)

#include <stdio.h>

int
main(void)
 {
    int f;
    int n;

    f = 1;
    for (n = 1 ; n <= 5 ; ++n)
        f = 3 * f + 4;
    printf("%d\n", f);

    return 0;
 }
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • It was fast. @fish0r, btw modern C++ compilers optimize recursion, so there won't be a stack overflow, it's a fine code. – Hi-Angel Jun 07 '15 at 16:55
  • thank you but the problem is that i can't use functions or any materials that i haven"t learn so far , the program should be in the main , use loops nothing else . – aaa Jun 07 '15 at 16:56
  • 1
    @Hi-Angel what has c++ to do with this? – Iharob Al Asimi Jun 07 '15 at 16:56
  • @iharob with what? I didn't understood the question. Don't you know what's stackoverflow? – Hi-Angel Jun 07 '15 at 16:57
  • @fish0r sorry but that wasn't clear in your question. – Iharob Al Asimi Jun 07 '15 at 16:57
  • 1
    There is no c++ involved in this question. And I believe it's pretty obvious that I do know what is stack overflow. – Iharob Al Asimi Jun 07 '15 at 16:57
  • Ah, okay, then C. Modern compilers compile both C++ and C ☺ – Hi-Angel Jun 07 '15 at 16:58
  • 1
    Microsoft compiler does... not modern compilers! – Iharob Al Asimi Jun 07 '15 at 16:59
  • @Hi-Angel it's a first class in c in the university , so there are some restrictions with building a code – aaa Jun 07 '15 at 16:59
  • @iharob well, of actively developing I acknowledged only of gcc, clang, msvc, and every compiler of these compile both C++ and C code. – Hi-Angel Jun 07 '15 at 17:04
  • They invoke each compiler separately, try to see what processes are running when you do `gcc c++.cpp` and `gcc c.c`. – Iharob Al Asimi Jun 07 '15 at 17:08
  • @iharob you're carp at my words. Of course I understand that they call different backends to compile the code, that wasn't what I meant. If you want — a package with compiler for C++ usually does have one for C code. – Hi-Angel Jun 07 '15 at 17:10
  • @Hi-Angel Ok, it's clear that **you** know the difference between c and c++, but normally new programmers don't, and it might make them think that there is none. – Iharob Al Asimi Jun 07 '15 at 17:11
  • @Hi-Angel : Do you have a citation for the assertion *"modern [...] compilers optimize recursion, so there won't be a stack overflow"*? I somehow doubt it; but would be interested if I were wrong. – Clifford Jun 07 '15 at 17:19
  • @Clifford well, at least I can for sure say that about msvc, GCC, and LLVM *(and hence clang)*. Even more — GCC can optimize mutual recursion *(it was -foptimize-sibling-calls, or something, but that option should be used with one more, I don't know which. These options enabled at least in -O2 level)*. – Hi-Angel Jun 07 '15 at 17:24
  • @Hi-Angel : That's not a citation. Forgive me for not just taking the word of someone on the Internet, but the Internet is full of nonsense as well as good information. This [article](https://msdn.microsoft.com/en-us/library/vstudio/z3dk2cc3%28v=vs.100%29.aspx) on MSDN for example, does not mention any such "optimisation". – Clifford Jun 07 '15 at 17:30
  • @Clifford well, okay, e.g. [here was a question about msvc and gcc tail recursion](http://stackoverflow.com/a/34129/2388257), and [here's documentation for LLVM tail call optimization](http://llvm.org/docs/CodeGenerator.html#tail-call-optimization). Also you may find at the [GCC documenation for optimize options the `-foptimize-sibling-calls`](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html) which also does this. – Hi-Angel Jun 07 '15 at 17:36
  • @Hi-Angel : Thanks for taking the time; I see now that it does not apply to recursion in general, but the special case when the recursive call is also a tail call. That makes more sense to me now. – Clifford Jun 07 '15 at 19:12
1

A LRE (linear recurrence equation) can be converted into a matrix multiply. In this case:

F(0) =  |  1  |   (the current LRE value)
        |  1  |   (this is just copied, used for the + 4)

M =     | 3 4 |   (calculates LRE             to new 1st number)
        | 0 1 |   (copies previous 2nd number to new 2nd number (the 1))

F(n) = M F(n-1) = matrixpower(M, n) F(0)

You can raise a matrix to the power n by using repeated squaring, sometimes called binary exponentiation. Example code for integer:

    r = 1;             /* result */
    s = m;             /* s = squares of integer m */
    while(n){          /* while exponent != 0 */
        if(n&1)        /*   if bit of exponent set */
            r *= s;    /*     multiply by s */
        s *= s;        /*   s = s squared */
        n >>= 1;       /*   test next exponent bit */
    }

For an unsigned 64 bit integer, the max value for n is 40, so the maximum number of loops would be 6, since 2^6 > 40.

If this expression was calculating f(n) = 3 f(n-1) + 4 modulo some prime number (like 1,000,000,007) for very large n, then the matrix method would be useful, but in this case, with a max value of n = 40, recursion or iteration is good enough and simpler.

rcgldr
  • 27,407
  • 3
  • 36
  • 61
  • It is worth mentioning that by using binary exponentiation, this approach is O(logn) instead of the other propsed solution which is O(n) – sbabbi Jun 07 '15 at 22:25
  • @sbabbi - I updated my answer to explain that repeated squaring is also called binary exponentiation. If you want, delete your comment and I'll delete this comment later. – rcgldr Jun 08 '15 at 04:49
-1

Best will be to use recursion . Learn it online .

Its is very powerful method for solving problems. Classical one is to calculate factorials. Its is used widely in many algorithms like tree/graph traversal etc.

Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem.

Here you break you problem of size n into 3 instance of sub problem of size n-1 + a problem of constant size at each such step.

Recursion will stop at base case i.e. the trivial case here for n=0 the function or the smallest sub problem has value 1.

cruxion effux
  • 1,054
  • 3
  • 14
  • 27
  • I would suggest against learning anything related to programming online, there are books for that. – Iharob Al Asimi Jun 07 '15 at 17:06
  • 1
    @iharob Its your thinking . And I don't see anything wrong with the answer and just downvote for this ? Yes books are good and yes they are a essential part of learning. But its not everybody has access to all things. Maybe you must be rich enough to buy book for everything but we do not have such money and we do most reading online. – cruxion effux Jun 07 '15 at 17:12
  • I didn't downvote your answer. There are many many many errors and bad practice in most of online programming tutorials. You don't need to be rich at all, I am very poor as a matter of fact, specially now that my country has a lot of economical problems, but you can search for books online too, specially if you're poor. – Iharob Al Asimi Jun 07 '15 at 17:13
  • Yes you can but most good books are not for free. And also not all things on programming online are not bad too. Its just that I am fed up yesterday I got downvoted for giving out code for trivial thing directly and today when I try to help by explaining instead of code I get downvoted again. Long live this community ! – cruxion effux Jun 07 '15 at 17:17
  • @iharob I'm against printed books for several reasons. When a book is printed, it's outdated already, especially CS books. A tree is killed. You read it once, then it covers dust most of the time. What for all that? I know that the author itself is first ripped off by the publisher, then by the mechandiser. What if the author emits only ebooks, thus bypassing publishers and merchandisers? He still can produce printed books for dinosaurs who like the feeling of dead trees in their hands. – ott-- Jun 07 '15 at 21:32
  • @ott I can't argue to that expect for the trees (*trees are data structures often found in those books!, is that what you mean*?) part, but if anything, searching for information about programming on the internet without a trained eye that tells you if you can trust the resource, means that you will learn cra* ... Today my sister asked for help with her programming class, and when I read what her teacher is recommending her to read, I wanted to cry... – Iharob Al Asimi Jun 07 '15 at 22:04
  • @iharob I mean a tree made of wood. My first source for online books is http://en.wikibooks.org/wiki/Main_Page – ott-- Jun 07 '15 at 22:59