HACKER RANK Project Euler 09 - Special Pythagorean Triplet - Solution.'C'

Project Euler Challenges-09 - Special Pythagoran Triplet Solution
Problem Statement
This problem is a programming version of Problem 9 from projecteuler.net
A Pythagorean triplet is a set of three natural numbers, a<b<c, for which,
a2+b2=c2

For example, 32+42=9+16=25=52
Given N, Check if there exists any Pythagorean triplet for which a+b+c=N 
Find maximum possible value of abc among all such Pythagorean triplets, If there is no such Pythagorean triplet print 1.
Input Format 
The first line contains an integer T i.e. number of test cases. 
The next T lines will contain an integer N.
Output Format 
Print the value corresponding to each test case in separate lines.
Constraints 
1T3000 
1N3000
Sample Input
2
12
4
Sample Output
60
-1

Solution:

#include <stdio.h>
#include <time.h>
int main()
{
  unsigned int i,j,t,n;
  long ans;
  scanf("%u",&t);
  while(t>0)
  {
    ans =-1;
    i=2;
    j=1;
    scanf("%u",&n);
    while(1)
    {
      int s = 2*i*i+2*i*j;
      if(s ==n )
      {
        long k = 2*i*j*(i*i+j*j)*(i*i-j*j);
        if (ans<k) ans =k;
        if(i>j+1) j++;
        else
        {
          j=1;
          i++;
        }
      }
      else if(s>n)
      {
        if(j==1) goto end;
        j=1;
        i++;
      }
      else
      {
        int new;
        for(new =2; s*new<=n;new++)
        {
          if(s*new == n)
          {
            long k = 2*i*j*(i*i+j*j)*(i*i-j*j)*new*new*new;
            if (ans<k) ans =k; 
          }
        }
        if(i>j+1) j++;
        else 
        {
          j=1;
          i++;
        }
      }
    }
    end: printf("%li\n",ans);
    t--;
  }
  return 0;
}

Thanks for Visiting, Hope this helps you....

Comments

Popular Posts