Time complexity and space of the function [duplicate] - c

This question already has answers here:
What is the time complexity of my function? [duplicate]
(4 answers)
Closed 6 years ago.
im sturggling with finding complexity of the next function
void what(int n) {
int i;
for (i = 1; i <= n; i++) {
int x = n;
while (x > 0)
x -= i;
}
}
ive tried to solve it by the next things
at looking on space i found its only O(1) since no taking of it.
when thinking of time
i thought that since its each time being devided it will be n(1+1/2 +1/4+....)=O(N.log(N))
is it correct?
thank you

A simplistic analysis gives a time complexity of O(N.log(N)), but it should be noted that the loop does not compute anything: local variable x is decremented n / i times and discarded. A good compiler should be able to compile the whole function to a no-op: void what(int n) {}, which a resulting complexity of O(1), both for space and time.

Related

Which loop is better? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Am a beginner at C here; Would like to ask which of the following 2 code is better for printing odd integers between 1 and given number?
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i+=2)
printf("%d ", i);
printf("\n");
}
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i++)
if (i%2 != 0)
printf("%d ", i);
printf("\n");
}
If neither can be said to be clearly "better", what are the different trade-offs between the versions?
Use the First Loop if n is not the extreme case like INT_MAX and also when i starts from an odd integer, Since it already skips half the number iterations.
Else use the Second Loop because the first will become infinite loop if n = INT_MAX.
Absolutely the first one.
Reasons:
- less lines of code
- branching statements (if, if else, switch cases, ...) are mainly avoided if there is other ways of handling the situation.
- time complexity of both algorithms are the same O(n). So this is mainly a matter of which code is more beatifull. And always remember, a code that is more readable is prettier.
EDIT
the fact that on the edge the first solution has undefined behavior is obvious. but these input validations must be checked outside the algorithm part. and it's much recommended that you DO NOT mix validation codes with your logic. easily you can check for i at first of the function and print INT_MAX if i==INT_MAX-1 or i==INT_MAX
Functionally, they are the same, so it really doesn't matter all that much unless you really need max performance.
However, the solution where you skip the if statement would be a lot efficient. You're skipping half the numbers and don't need to check a condition with modulus.
Both loops have undefined behavior if n == INT_MAX because of arithmetic overflow.
The first loop will potentially give you better performance
The second loop is potentially more readable (for a beginner) and less error prone if you later change the code to start from an arbitrary value.
I would use braces around the for body as it is not a simple one line statement and spaces around binary operators to improve readability:
void print_odd_integers(int n) {
int i;
for (i = 1; i <= n; i++) {
if (i % 2 != 0)
printf("%d ", i);
}
printf("\n");
}
Note also that both loops will output a space after the last number before the newline, which may be incorrect.
You can address both issues with one extra test:
void print_odd_integers(int n) {
for (int i = 1; i <= n; i += 2) {
printf("%d", i);
if (i == n)
break;
}
printf("\n");
}
The second solution is the "professional" way.
One thing you could change would be the Layout:
void print_odd_integers(int n)
{
int i;
for (i=1; i<=n; i++)
{
if (i%2 != 0)
{
printf("%d\n", i);
}
}
printf("End.\n");
system("Pause"); //So you can see what you did :)
}
Have fun :)!

C - Count the number of combinations possible in a string without repetitions [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Good night, what's the best way in C to count the number of possibilities of UNIQUE anagrams in a string with the maximum length of 256 without allows repetitions caused by same letters? The input would be just in uppercase and only alphabet letters are allowed, A-Z. I got stuck in the worst case of the program that got 26! a very large number that overflow even my double. I think I'm very lost here, I'm not so good in C. The program just need to shows the number of possibilities, not the anagram. Like:
LOL = 3
HOUSE = 120
OLD = 6
ABCDEFGHIJKLMNOPQRSTUVWXYZ = 403291461126605635584000000
Thank you guys very much... I tried a lot and failed in every single tried, I'm in distress with it. The way I got more closer of do it was in Pascal, but it also failed in some tests, and I can't use Pascal anyway. I'm using CodeBlocks on Windows that compiles with GCC.
You should calculate factorial of the length of the given string divided by the factorial of the occurrence of every letter.
long double logFactorial (int i) {
return i < 2 ? 0.L : (logFactorial (i-1)+log(long double (i));
}
int countLetter(const char* str, char c) {
int res = 0;
while (str && *str) {
res += *str++ == c;
}
return res;
}
long double numPermutations(const char* str) {
auto res = logFactorial (strlen(str));
for (char c = 'A'; c<='Z'; c++) {
res -= logFactorial (countLetter (str,c));
}
return exp((long double)res);
}
Pay attention!
There are several people here who were correct by saying that factorial of 26 cannot be stored even in 64bit integer.
Therefore, I changed my calculation to the logarithmic of the factorial number and store it in long double which I hope is precise enough (I think that the exp() function is not precise enough)
Nevertheless you cannot use this result as an integer value, unless you find a way to store it in 128bit integer or bigger...
You should test it too if this fits your problem.
There is a faster way to calculate the factorial for this problem by storing the results of 0! up to 26! in an array of the size of [27].
I will leave it to you for asking another question.

What is the complexity of the following simple program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am having trouble finding understanding complexity. Could someone help me understand what the complexity of the code below is and why.
for (int i = 1; i < n; i++) { // (n is a number chosen by the user)
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
An explanation would be great.
Assuming i starts at 0, the complexity would be constant. The complexity is always expressed relative to a variable defining the number of executions, which is not the case here.
If one term should be used to describe this behavior, it is "constant". There will be a number of executions, but this number will never change
Original Question: Because i's initial value is undefined, the behavior of the code is unpredictable. There is no way to usefully answer the question other than that the complexity is undefined. There is no way to know how many operations the code will perform.
Updated Question: It's O(1). The code will always do precisely the same amount of work.
You can compute the time complexity of this code fragment by evaluating the number of operations, namely the number of calls to printf() which for simplicity's sake we shall assume to be equivalent:
Assuming i starts at 1 (you initially forgot to initialize it), the outer loop runs 99 times, for each iteration, the inner loop runs i times. Gauss was supposedly 9 years old when he computed the resulting number of iterations to be 99 * (99 + 1) / 2.
The complexity of the original piece of code was O(1) since it did not depend on any variable, but since instead you updated the code as:
void fun(int n) {
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
}
The time complexity would come out as O(n2).

Nested whiles in C [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
int count(int *a, int *b, int n) {
int i=0,j=0,roz=0;
while(i<n) {
while(j<n) {
if(a[i]==b[j])
roz++;
j++;
}
i++;
}
return roz;
}
n is the size of a, or b array (both are of the same size). The nested while loop seems to work only once, for i = 0. The next thing that seems to be happening is magically changing n into 1 (it is 5 at the beginning), so that the nested while doesn't loop the second time. Why is that so?
The interesting thing is that echoing n right before the return displays the right value, which is 5...
EDIT. For loops work properly here, but the question is still present.
You never reset the value of j to 0.
You should reset j to 0 between two nested loops.
while (i < n)
{
j = 0;
while (j < n)
{
if (a[i] == b[j])
roz++;
}
}
You could compute the intersection of two arrays in a more efficient way (there is a O(N*log N) solution).
The value of n is not changed here. The reason nested loop is not executing for i = 1 or later is that you are not resetting the value of j. Say, n is 5. When i = 0 nested loop executes properly and the value of j is 5 after it finishes. When i = 1 then j is still 5 and so it never enters the nested loop.
while(i<n)
{
j = 0; // reset j here to solve the problem
while(j<n) {}
Well by looking at the logic,it seems that you are conuting the number of common elements in both the arrays.
the mistake you are doing is you are not resetting the value of j to 0 in the first while loop.

Write recursive function that prints 1 and n zeroes in C [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have trouble writing a recursive function in C:
void func(int n)
which for a given number n prints "1" and n zeroes after it.
for example:
func(3);
prints: 1000
func(5);
prints: 100000
No global variables (outside the function) are allowed and argument count must not be increased. No other helper functions allowed.
Just some pointers:
Why do you think you must print "1" only on the first call of the function?
Why can't you print it on the last call of the recursive function and then print all the 0's?
How will you determine if a call to the function is the last call in the recursive way? (Can the value of "n" hold the answer?)
I would suggest you look into static variables. you could set a static variable to tell if your function is being called recursively or not. If you're not allowed to use global variables, it's just a tricky work-around. And when your recursion is done, just set it back for the next call.
You can solve this problem using two functions, for example func and func_rec. func will print the 1 and it will once call the recursive function func_rec which will print only zeros (recursively).
#include <stdio.h>
void func(int k){
if(k==0){
printf("1");
return;
}
func(k-1);
printf("0");
}
int main(){
func(3);
return 0;
}
#include <stdio.h>
void func(int n)
{
static one = 1;
if (one == 1){
printf("1");
one--;
func(n - 1);
}
else {
if (n < 0){
printf("\n");
return;
}
else {
printf("0");
func(n - 1);
}
}
}
int main() {
func(5);
return 0;
}
The code is very trivial so, even it seems that its a homework, i'm giving out the code.
Your earlier question suggests that you are not so much into c coding. What i'm trying to do is to reduce your frustration by giving out the code, but with a twist.
Please answer us why the code i've given is not a "pure" function? why this solution should be discarded with ones which have global storage.
You should learn this stuff, its pretty interesting :)

Resources