Pythagorean Pair CodeChef Solution

Problem -Pythagorean Pair CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Pythagorean Pair CodeChef Solution in C++17

#include <bits/stdc++.h>
using namespace std;
typedef long long mm;
int main() {
	// your code goes here
	int t;cin>>t;
	while(t--){
	    bool flag =true;
	    mm n;cin>>n;
	    mm x=0;
	    while(n%2==0){
	        x++;n/=2;
	    }if(x%2==1){x-=1;n=n*2;}
	    for(int i=0;i*i<=n;i++){
	        int a=n-i*i;
	        int b=sqrt(a);
	        if(b*b==a){
	            cout<<(b<<(x/2))<<" "<<(i<<(x/2))<<"\n";
	            flag=false;break;
	        }
	    }
	    if(flag)cout<<-1<<"\n";
	}
	return 0;
}

Pythagorean Pair CodeChef Solution in C++14

#include <bits/stdc++.h>
using namespace std;
void solve()
{
    long long n;
    cin >> n;
    int count = 0;
    while (n % 4 == 0)
    {
        count++;
        n /= 4;
    }
    bool flag = false;
    for (long long i = 0; i <= sqrt(n); i++)
    {
        double j = sqrt(n - i * i);
        if (j == (int)j)
        {
            flag = true;
            cout << i * (1 << count) << " " << (int)j * (1 << count) << endl;
            break;
        }
    }
    if (!flag)
    {
        cout << "-1" << endl;
    }
}
int main()
{
    int t = 1;
    cin >> t;
    while (t--)
    {
        solve();
    }

    return 0;
}

Pythagorean Pair CodeChef Solution in PYTH 3

import math

def solve():
    n = int(input())
    x = 0
    while n % 2 == 0:
        x += 1
        n //= 2
    if x % 2 == 1:
        x -= 1
        n *= 2
    for i in range(int(math.sqrt(n))+1):
        y = n - i*i
        z = int(math.sqrt(y))
        if z*z == y:
            print((z<<(x//2)), (i<<(x//2)))
            return
    print(-1)

t = int(input())
while t > 0:
    t -= 1
    solve()
# for _ in range(int(input())):
#     n=int(input())
#     N = int(n**0.5)
    
#     squares = [int(y)**2 for y in range(1,N+1)]
   
    
    
#     flag = True
    
#     for i in squares:
#         for x in squares:
#             if i+x==n and flag:
#                 print(int(i**0.5),int(x**0.5))
#                 flag = False
               
#     if flag:
#         if n==N*N:
#             print(0,N)
#         else:    
#             print(-1)
    
          
                

Pythagorean Pair CodeChef Solution in C

#include <stdio.h>
#define int long long
int n, x;
void solve()
{
    scanf("%lld", &n);
    x = 0;
    while (n % 2 == 0)
    {
        x++;
        n /= 2;
    }
    if (x % 2 == 1)
    {
        x--;
        n *= 2;
    }
    for (int i = 0; i * i <= n; ++i)
    {
        int y = n - i * i, z = sqrt(y);
        if (z * z == y)
        {
            printf("%lld %lld\n", (z << (x / 2)), (i << (x / 2)));
            return;
        }
    }
    printf("-1\n");
}
signed main()
{
    int T;
    scanf("%lld", &T);
    while (T--)
        solve();
}

Pythagorean Pair CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{
	    Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		while(t-->0){
		    long n=sc.nextLong();
		    long mul = 1L;
		    while (n % 4 == 0)
            {
                mul *= 2;
                n /= 4;
            }
            boolean f=false;
		    for(long i=0;i*i<=n && !f;i++){
		        long bb=n-i*i;
		        long b=(long)Math.sqrt(bb);
		        if(b*b==bb){
		            System.out.println(i*mul+" "+b*mul);
		            f=true;
		        }    
		    }
		    if(!f)
    		    System.out.println(-1);
    		    
    		    
		}
		// your code goes here
	}
}

Pythagorean Pair CodeChef Solution in PYPY 3

#Don't stalk me, don't stop me, from making submissions at high speed. If you don't trust me,
import sys
#then trust me, don't waste your time not trusting me. I don't plagiarise, don't fantasize,
import os
#just let my hard work synthesize my rating. Don't be sad, just try again, everyone fails
from io import BytesIO, IOBase
BUFSIZE = 8192
#every now and then. Just keep coding, just keep working and you'll keep progressing at speed-
# -forcing.
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
#code by _Frust(CF)/Frust(AtCoder)
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from os import path
if(path.exists('input.txt')):
    sys.stdin = open("input.txt","r")
    sys.stdout = open("output.txt","w")
    input = lambda: sys.stdin.readline().rstrip("\r\n")

d1={}
pow2=[1]*61
N=int(2e5) + 5

def precal():
    for i in range(N):
        if i*i>N:
            break
        d1[i*i]=i

    for i in range(1, 61):
        pow2[i]=pow2[i-1]*2

precal()


for _ in range(int(input())):
    n=int(input())
    po2=0
    while n%2==0:
        n//=2
        po2+=1

    if po2%2==1:
        po2-=1
        n*=2

    flag=1
    a=-1
    b=-1
    for i in range(n):
        if i*i>n:
            break
        bval=n-i*i
        if bval in d1:
            flag=0
            a=i
            b=d1[bval]
            break

    if flag:
        print(-1)
    else:
        print(a*pow2[po2//2], b*pow2[po2//2])

    

Pythagorean Pair CodeChef Solution in NODEJS

// process.stdin.resume();
// process.stdin.setEncoding('utf8');

// // your code goes here

// let inputString = ''
// let currentLine = 0

// process.stdin.on('data',(input)=>{
//     inputString += input
// })

// process.stdin.on('end',()=>{
//     inputString = inputString.split('\n').map((str)=>str.trim())
//     main()
// })

// function readLine(){
//     return inputString[currentLine++]
// }
// function isPerfectSquare(n){
    
//     let i = 1
//     while((i*i)<n){
//         i++
//     }
//     if((i*i)==n){
//         return i
//     }
//     return false
// }
// function main(){
//       const t = parseInt(readLine())
//     for(let z = 0;z<t;z++){
//         let n = readLine()
//         let i = 0
//         let ans = -1
//         while((i*i)<=n){
//             let k = Math.floor(Math.sqrt(n-(i*i)))
//             if(((i*i) + (k*k)) == n){
//                 ans = i+' '+k
//                 break
//             }
//             i++
//         }
//         console.log(ans)
        
        
//     }
// }


process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here


// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});


function start() {
    t = parseInt(lines[0])
    let line = 1
    let possible
    while (t > 0) {
        let N = parseInt(lines[line++].split(' ')[0], 10)
        let i = 0;
        let k = 0;
        while (N % 2 == 0) {
            k++
            N /= 2
        }
        if (k % 2 == 1) {
            k --
            N *= 2
        }
        let max = Math.sqrt(N)
        for(i = 0; i <= max; i++) {
            const b = parseInt(Math.sqrt(N - i * i), 10)
            if ((i * i + b * b) == N) {
                console.log(i * Math.pow(2, k/2), b * Math.pow(2, k/2))
                break
            }
        }
        if (i > max) {
            console.log(-1)
        }
        t--
    }
}

Pythagorean Pair CodeChef Solution in GO

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"math"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		var n uint64
		s, _ := reader.ReadBytes('\n')
		readUint64(s, 0, &n)
		A, B := solve(int64(n))
		if A < 0 {
			buf.WriteString("-1\n")
		} else {
			buf.WriteString(fmt.Sprintf("%d %d\n", A, B))
		}
	}

	fmt.Print(buf.String())
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func solve(n int64) (int64, int64) {
	num := n
	for num%2 == 0 {
		num /= 2
	}

	x := int64(math.Sqrt(float64(num)))

	for a := int64(0); a < x; a++ {
		A := a * a
		B := num - A
		b := int64(math.Sqrt(float64(B)))
		if b*b == B {
			// a solution
			for num != n {
				a, b = a+b, abs(a-b)
				num *= 2
			}
			return a, b
		}
	}
	return -1, -1
}

func abs(num int64) int64 {
	if num < 0 {
		return -num
	}
	return num
}
Pythagorean Pair CodeChef Solution Review:

In our experience, we suggest you solve this Pythagorean Pair CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Pythagorean Pair CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Pythagorean Pair CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *