Slow execution of a repeat problem is in c [closed]

0

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

Could anyone 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.

     

Entry

     

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

     

Output

     

The output must contain one line for each computed square. Each line shall contain an expression   of type xˆ2 = y , where x is an even number and y is its squared value. Immediately   after the y value should 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;
}
    
asked by anonymous 10.10.2018 / 00:54

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;
}
    
10.10.2018 / 01:10