I did this in c :
#include<stdio.h>
int main (void)
{
int n,i;
scanf("%d", &n);
for(i=2;i<=n;i=i+2)
{
if((i*i)%2==0 && (i*i)<= n)
printf("%d \n",(i*i));
}
return 0;
}
What would be a better/faster approach to tackle this problem?
Let me illustrate not only a fast solution, but also how to derive it. Start with a fast way of listing all squares and work from there (pseudocode):
So, starting from 4 and listing only even squares:
Now we can shorten that mess on the end of the while loop:
Note that we are constantly using
2*d, so it’s better to just keep calculating that:Now note that we are constantly adding
2 + d, so we can do better by incorporating this intod:Blazing fast. It only takes two additions to calculate each square.