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).
Related
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 2 months ago.
Improve this question
Good evening. I had a coding interview on Codesignal with the question below, and I got just 14/20 with the test cases. How will you solve it please.
Given an array of nums, add positive and negative in succession and return the sum.
Example : given nums = {2, 3, 4, 5, 7}
Answer = 2-3+4-5+7 = 5.
What's the fastest algorithm for this?
I tried to use a two for loops and input -ve with i+1 for the second loop, but that's just brute force and terribly slow
There is no way to avoid an exhaustive accumulation of the values, but this is terribly... fast. There is no need and no way to accelerate, besides unrolling the loop (which will probably have little effect) and parallelizing (out of the scope of the question).
IMO, the most reasonable way is with
int sum= 0; int i;
for (i= 0; i + 1 < n; i+= 2)
{
sum+= num[i] - num[i+1];
}
if (i < n)
{
sum+= num[i];
}
If the data is int32, positive, and the processor 64 bits, a nasty hack would be to load two values at a time as 64 bits and accumulate this way. In the end, you split back to 32 bits and perform the final subtraction. But again, I doubt the this will yield a significant speedup.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
This is code written by me where I have to print a single integer denoting the minimum possible capacity of a tram (0 is allowed). It's a problem from codeforces. The answer in CodeBlocks is showing 6 (the right answer) but in codeforces compiler I'm getting another output.
Why is this happening?
#include <stdio.h>
int main() {
int n, i, j, max = 0, sum = 0;
int pssnger_left;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &a[i][j]); // declaring the value of array
}
}
pssnger_left = a[0][0] + a[0][1];
for (i = 1; i < n; i++) {
sum = pssnger_left - a[i][0];
sum = sum + a[i][i];
pssnger_left = sum;
if (max < sum)
max = sum;
}
printf("%d", max);
}
Input:
4
0 3
2 5
4 2
4 0
Output:
4221555
Answer:
6
Checker Log
wrong answer expected 6, found 4221555
Here is the link of the problem: https://codeforces.com/problemset/problem/116/A
Different compiler, different answer, 99% of the cases is explained by Undefined Behaviour, UB.
In the shown code here it is a[i][i];.
For any i > 1 that is not what you want it to be
and for most high i it illegally accesses beyond a.
-> Undefined Behaviour.
A hint on how I spotted this:
Whenever I see [i][i], actually whenever I see [same][same],
I think "diagonal in a square". And in your code I immediatly thought "What square?", because when seeing int a[n][2]; I thought "Long narrow table." and got a conflict of shapes there.
The problem is not basically with the compiler.
You are doing
sum = sum + a[i][i];
but you have declared a 2D array of n x 2 i.e. int a[n][2]
see in some compilers it shows out of bound because you are accessing an element which is not there in the array
and in compilers it just loops in the already existing array for ex if your array has 5 elements and you are trying to access 6th element then it will go back to 1st index,
so this might be whats happening here.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to programming and I'm following the CS50 course. I'm trying to fully understand the logic behind nested loops in C. I think I've got it, but I'd like to be sure before I move on to the next set of problems. Here's the code (provided by the course). It creates a cube made of hashes. My explanations are below the code.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n, j++)
{
printf("#");
}
printf("\n");
}
The first loop starts: It creates a new variable called i and sets it to 0. The command checks the new variable: If it is lesser than n (true), run it, starting the inside loop.
The inside loop also creates a new variable, j, sets it to 0, checks it and, if it is true (j < n), runs the code below and print a hash. Afterwards, the inside loop is incremented and this process occurs again until the inside loop condition is not met anymore. This will create a ROW of hashes if n is greater than 2.
The outer loop creates a new line, increments and the process starts all over again. It will run until the condition is false (i > n).
The next times the inside loop is accessed, the variable j is set to 0 again, that's why it is possible to print various rows in this program.
Is that correct? Thank you very much in advance!
Yes, your explanation is spot on.
With a minor mistake:
It will run until the condition is false (i > n).
The condition is false when i >= n.
And what I assume it's a typo:
for (int j = 0; j < n, j++);
// ^
// |
remove the ;
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 4 years ago.
Improve this question
I am trying to create an application in C that finds three similar elements in an array. For example, 1 2 3 4 3 5 3 and three is repeated three times using nested for loops.
You need to be more clear about your question...
This code will help you if you want to find only the first triple.
And I will refer to the above writers, if this is your HW, its only hurts you.
int findrpt(int* arr,int len){
int cnt = 0;
int i = 0, j = 0;
for(i = 0; i < len; i++)
{
cnt = 0;
for(j = i; j < len - i; j++)
if(arr[j] == arr[i])
cnt++;
if(cnt >= 3)
return arr[i];
}
}
Why use nested loops? its basically O(n^3) time. Basically just sort the array in time O(nlogn) and find the element using single for loop. Benefit of sorting. In case you want to find all triples only then a single loop is required but if you want to check if some specific element is occurs three times, just apply binary search.
If the input elements are restricted to a smaller range like [1,100], you can use a counter array of length 1000 initialized as counter[[i]] = 0 . Now just run a single loop and increment the counter as:
for(i = 0 to length of input_array - 1)
{
counter[input_array[i]]++;
}
if(counter[i] == 3)
input_array[i] is a triplet
In this case you wont even require sorting. Cause the array counter will have the count of each element.
If you want to go nested loops, you can make three nested loops, initialized from 0 to 2 elements of the array and check the condition.
There are other easy ways too.
sort the array and check the condition
Count elements
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 :)!