HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Project Euler #9 in C: Special Pythagorean triplet

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythagoreantripletprojectspecialeuler

Problem

I have finished Project Euler #9 on HackerRank:


Given \$N\$, Check if there exists any Pythagorean triplet for which \$a+b+c=N\$, \$a^2+b^2=c^2\$.
Find maximum possible value of \$abc\$ among all such Pythagorean triplets, and if there is no such Pythagorean triplet print −1.

However, I feel uncomfortable about my code. I think it is sort of spaghetti code that is neither well organized nor fast (just a feeling).

Optimization and simplification is needed. (For example, there are many nested ifs).

#include 
#include 
int main()
{
  clock_t start = clock();
  unsigned int i,j,t,n;
  long p;
  scanf("%u",&t);
  while(t>0)
  {
    p =-1;
    i=2;
    j=1;
    scanf("%u",&n);
    while(1)
    {
      int s = 2*i*i+2*i*j;
      if(s ==n )
      {
        long o = 2*i*j*(i*i+j*j)*(i*i-j*j);
        if (pj+1) j++;
        else
        {
          j=1;
          i++;
        }
      }
      else if(s>n)
      {
        if(j==1) goto end;
        j=1;
        i++;
      }
      else
      {
        int counter;
        for(counter =2; s*counterj+1) j++;
        else 
        {
          j=1;
          i++;
        }
      }
    }
    end: printf("%li\n",p);
    t--;
  }
  clock_t end = clock();
  printf("time in milliseconds %lf\n",(double)(end-start)*1000/CLOCKS_PER_SEC);
  return 0;
}

Solution

Just few remarks:

  • Variables with meaningful names are more useful and make the code easier to read and understand.



  • Comments add to code clarity and could possibly point to fragments that can be optimized.



-
Use a more compact brace style.

int foo()
{
    for
      {
          //...
      }
}


could become

int foo(){
    for{
         //...
       }
}


-
Add white space between operands and operations: (a + b; a == b; a = 1).

  • Consistency and style: eliminate random white spaces/ indentations in expressions (p =1, p=1 or p= 1)



  • Brake the code into functions, each with single task.

Code Snippets

int foo()
{
    for
      {
          //...
      }
}
int foo(){
    for{
         //...
       }
}

Context

StackExchange Code Review Q#90974, answer score: 5

Revisions (0)

No revisions yet.