Slow execution of a repeat problem for c

Asked

Viewed 67 times

0

I made this algorithm for the problem below. It works and returns the desired value. However it is running slow for the size of the problem and the tool, which fixes the problems, is not accepting the same as certain.

Could someone help me ?

Problem:

Write a program to read an integer value N and generate the square of each of the even values, from 1 to N, including N, if applicable.

Entree

The entry will contain a row with an integer value N, 5 < N < 2000.

Exit

The output must contain, one line for each square computed. In each single l an expression must be of the kind xˆ2 = y, where x is an even number and y is its high value squared. Immediately after the value of y must appear the line break character: \n.

Example

Entrada
6
Saída
2ˆ2 = 4
4ˆ2 = 16
6ˆ2 = 36

My code:

#include<stdio.h>
#include<stdlib.h>



int main(){

    int n,i;

    scanf("%d",&n);
if((n%2)==0){
    for(i=2; i<=n; i = i+2){
            printf(" %d ^ 2 =  %d\n",i, i*i);
    }
}
else
    for(i=2; i<n; i = i+2){
            printf(" %d ^ 2 =  %d\n",i, i*i);
    }
      return 0;
}
  • It’s very confusing what you should do and the question of time. Give more details, put it in a more organized way to see if there is any other detail, because there is not much you can do to get faster, can give a small gain, but is tiny. They gave you an answer that makes it worse.

  • "slow running" - How slow are we talking ? How long does it take ? What’s the time limit ? What’s the platform ?

  • Apparently it’s some sort of URI-style auto-correction site, these sites can indicate timeout when the program takes too long to give the result. This "lot" indicates that the program has a complexity (type O(n²)) greater than necessary

1 answer

3


Your algorithm is making unnecessary comparisons, try it this way:

#include<stdio.h>

int main(){

    int n, i;

    scanf("%d", &n);

    n/=2;

    for(i=1; i<=n; i++)
         printf(" %d ^ 2 =  %d\n", 2*i, 4*i*i);

    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.