Generate Pythagorean Triplets
Last Updated :
23 Jul, 2025
Given a positive integer limit, your task is to find all possible Pythagorean Triplet (a, b, c), such that a <= b <= c <= limit.
Note: A Pythagorean triplet is a set of three positive integers a, b, and c such that a2 + b2 = c2.
Input: limit = 20
Output: 3 4 5
5 12 13
6 8 10
8 15 17
9 12 15
12 16 20
Explanation: All the triplets are arranged in the format (a, b, c), where a2 + b2 = c2.
[Naive Approach] - Using Nested Loops - O(n ^ 3) Time and O(1) Space
The idea is to use nested loops to generate all possible combinations of a, b, and c. For each combination check if a2 + b2 = c2, if the condition satisfies store the triplet, else move to next combination.
C++
// C++ program to find all Pythagorean
// Triplets smaller than a given limit
#include<bits/stdc++.h>
using namespace std;
// Function to generate all Pythagorean
// Triplets smaller than limit
vector<vector<int>> pythagoreanTriplets(int limit) {
// to hold the triplets
vector<vector<int>> ans;
for(int a = 1; a<=limit; a++) {
for(int b = a; b<=limit; b++) {
for(int c = b; c<=limit; c++) {
if(a * a + b * b == c * c) {
ans.push_back({a,b,c});
}
}
}
}
return ans;
}
int main() {
int limit = 20;
vector<vector<int>> ans = pythagoreanTriplets(limit);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < 3; j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}
C
// C program to find all Pythagorean
// Triplets smaller than a given limit
#include <stdio.h>
void pythagoreanTriplets(int limit) {
// to hold the triplets
int a, b, c;
for(a = 1; a <= limit; a++) {
for(b = a; b <= limit; b++) {
for(c = b; c <= limit; c++) {
if(a * a + b * b == c * c) {
printf("%d %d %d\n", a, b, c);
}
}
}
}
}
int main() {
int limit = 20;
pythagoreanTriplets(limit);
return 0;
}
Java
// Java program to find all Pythagorean
// Triplets smaller than a given limit
import java.util.*;
class GFG {
// Function to generate all Pythagorean
// Triplets smaller than limit
static List<List<Integer>> pythagoreanTriplets(int limit) {
// to hold the triplets
List<List<Integer>> ans = new ArrayList<>();
for(int a = 1; a <= limit; a++) {
for(int b = a; b <= limit; b++) {
for(int c = b; c <= limit; c++) {
if(a * a + b * b == c * c) {
ans.add(Arrays.asList(a, b, c));
}
}
}
}
return ans;
}
public static void main(String[] args) {
int limit = 20;
List<List<Integer>> ans = pythagoreanTriplets(limit);
for (List<Integer> triplet : ans) {
for (int num : triplet) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
Python
# Python program to find all Pythagorean
# Triplets smaller than a given limit
def pythagoreanTriplets(limit):
# to hold the triplets
ans = []
for a in range(1, limit + 1):
for b in range(a, limit + 1):
for c in range(b, limit + 1):
if a * a + b * b == c * c:
ans.append([a, b, c])
return ans
# Driver code
limit = 20
ans = pythagoreanTriplets(limit)
for triplet in ans:
for num in triplet:
print(num, end=" ")
print()
C#
// C# program to find all Pythagorean
// Triplets smaller than a given limit
using System;
using System.Collections.Generic;
class GFG {
// Function to generate all Pythagorean
// Triplets smaller than limit
static List<List<int>> pythagoreanTriplets(int limit) {
// to hold the triplets
List<List<int>> ans = new List<List<int>>();
for(int a = 1; a <= limit; a++) {
for(int b = a; b <= limit; b++) {
for(int c = b; c <= limit; c++) {
if(a * a + b * b == c * c) {
ans.Add(new List<int> { a, b, c });
}
}
}
}
return ans;
}
static void Main() {
int limit = 20;
List<List<int>> ans = pythagoreanTriplets(limit);
foreach (List<int> triplet in ans) {
foreach (int num in triplet) {
Console.Write(num + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// JavaScript program to find all Pythagorean
// Triplets smaller than a given limit
function pythagoreanTriplets(limit) {
// to hold the triplets
let ans = [];
for(let a = 1; a <= limit; a++) {
for(let b = a; b <= limit; b++) {
for(let c = b; c <= limit; c++) {
if(a * a + b * b === c * c) {
ans.push([a, b, c]);
}
}
}
}
return ans;
}
// Driver code
let limit = 20;
let ans = pythagoreanTriplets(limit);
for (let triplet of ans) {
console.log(triplet.join(" "));
}
Output3 4 5
5 12 13
6 8 10
8 15 17
9 12 15
12 16 20
Time Complexity: O(n3), where n is representing the limit.
Space Complexity: O(1)
[Expected Approach] - Using Two Pointers - O(n ^ 2) Time and O(1) Space
The idea is to use Two Pointers to generate combinations of a & b in linear time, and check if a2 + b2 = c2. To do so, iterate through all values of c from 1 to limit, and set a = 1, and b = c - 1. At each iteration there are three possibilities:
- if a2 + b2 > c2: Decrease the value of b by 1.
- if a2 + b2 < c2: Increase the value of a by 1.
- if a2 + b2 = c2: Store the triplet
C++
// C++ program to find all Pythagorean
// Triplets smaller than a given limit
#include<bits/stdc++.h>
using namespace std;
// Function to generate all Pythagorean
// Triplets smaller than limit
vector<vector<int>> pythagoreanTriplets(int limit) {
// to hold the triplets
vector<vector<int>> ans;
for(int c = 1; c<=limit; c++) {
int a = 1, b = c - 1;
while (a <= b) {
if (a * a + b * b == c * c) {
ans.push_back({a,b,c});
break;
}
else if (a * a + b * b < c * c) {
a++;
}
else {
b--;
}
}
}
return ans;
}
int main() {
int limit = 20;
vector<vector<int>> ans = pythagoreanTriplets(limit);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < 3; j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}
Java
// Java program to find all Pythagorean
// Triplets smaller than a given limit
import java.util.*;
class GFG {
// Function to generate all Pythagorean
// Triplets smaller than limit
static List<List<Integer>> pythagoreanTriplets(int limit) {
// to hold the triplets
List<List<Integer>> ans = new ArrayList<>();
for(int c = 1; c <= limit; c++) {
int a = 1, b = c - 1;
while (a <= b) {
if (a * a + b * b == c * c) {
ans.add(Arrays.asList(a, b, c));
break;
}
else if (a * a + b * b < c * c) {
a++;
}
else {
b--;
}
}
}
return ans;
}
public static void main(String[] args) {
int limit = 20;
List<List<Integer>> ans = pythagoreanTriplets(limit);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < 3; j++) {
System.out.print(ans.get(i).get(j) + " ");
}
System.out.println();
}
}
}
Python
# Python program to find all Pythagorean
# Triplets smaller than a given limit
def pythagoreanTriplets(limit):
# to hold the triplets
ans = []
for c in range(1, limit + 1):
a, b = 1, c - 1
while a <= b:
if a * a + b * b == c * c:
ans.append([a, b, c])
break
elif a * a + b * b < c * c:
a += 1
else:
b -= 1
return ans
# Driver code
limit = 20
ans = pythagoreanTriplets(limit)
for i in range(len(ans)):
for j in range(3):
print(ans[i][j], end=" ")
print()
C#
// C# program to find all Pythagorean
// Triplets smaller than a given limit
using System;
using System.Collections.Generic;
class GFG {
// Function to generate all Pythagorean
// Triplets smaller than limit
static List<List<int>> pythagoreanTriplets(int limit) {
// to hold the triplets
List<List<int>> ans = new List<List<int>>();
for(int c = 1; c <= limit; c++) {
int a = 1, b = c - 1;
while (a <= b) {
if (a * a + b * b == c * c) {
ans.Add(new List<int> { a, b, c });
break;
}
else if (a * a + b * b < c * c) {
a++;
}
else {
b--;
}
}
}
return ans;
}
public static void Main() {
int limit = 20;
List<List<int>> ans = pythagoreanTriplets(limit);
for (int i = 0; i < ans.Count; i++) {
for (int j = 0; j < 3; j++) {
Console.Write(ans[i][j] + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// JavaScript program to find all Pythagorean
// Triplets smaller than a given limit
function pythagoreanTriplets(limit) {
// to hold the triplets
let ans = [];
for(let c = 1; c <= limit; c++) {
let a = 1, b = c - 1;
while (a <= b) {
if (a * a + b * b === c * c) {
ans.push([a, b, c]);
break;
}
else if (a * a + b * b < c * c) {
a++;
}
else {
b--;
}
}
}
return ans;
}
// Driver code
let limit = 20;
let ans = pythagoreanTriplets(limit);
for (let i = 0; i < ans.length; i++) {
for (let j = 0; j < 3; j++) {
process.stdout.write(ans[i][j] + " ");
}
console.log();
}
Output3 4 5
6 8 10
5 12 13
9 12 15
8 15 17
12 16 20
Time Complexity: O(n2), where n is representing the triplets.
Space Complexity: O(1)
[Alternate Approach] - Using Mathematics
Note: The below given method doesn't generate all triplets smaller than a given limit. For example "9 12 15" which is a valid triplet is not printed by above method.
The idea is to use square sum relation of Pythagorean Triplet that states that addition of squares of a and b is equal to square of c. We can write these numbers in terms of m and n such that,
a = m2 - n2
b = 2 * m * n
c = m2 + n2
because,
a2 = m4 + n4 – 2 * m2 * n2
b2 = 4 * m2 * n2
c2 = m4 + n4 + 2* m2 * n2
We can see that a2 + b2 = c2, so instead of iterating for a, b and c we can iterate for m and n and can generate these triplets.
C++
// C++ program to generate pythagorean
// triplets smaller than a given limit
#include <bits/stdc++.h>
// Function to generate pythagorean
// triplets smaller than limit
void pythagoreanTriplets(int limit)
{
// triplet: a^2 + b^2 = c^2
int a, b, c = 0;
// loop from 2 to max_limit
int m = 2;
// Limiting c would limit
// all a, b and c
while (c < limit) {
// now loop on j from 1 to i-1
for (int n = 1; n < m; ++n) {
// Evaluate and print triplets using
// the relation between a, b and c
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
if (c > limit)
break;
printf("%d %d %d\n", a, b, c);
}
m++;
}
}
// Driver Code
int main()
{
int limit = 20;
pythagoreanTriplets(limit);
return 0;
}
Java
// Java program to generate pythagorean
// triplets smaller than a given limit
import java.io.*;
import java.util.*;
class GFG {
// Function to generate pythagorean
// triplets smaller than limit
static void pythagoreanTriplets(int limit)
{
// triplet: a^2 + b^2 = c^2
int a, b, c = 0;
// loop from 2 to max_limit
int m = 2;
// Limiting c would limit
// all a, b and c
while (c < limit) {
// now loop on j from 1 to i-1
for (int n = 1; n < m; ++n) {
// Evaluate and print
// triplets using
// the relation between
// a, b and c
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
if (c > limit)
break;
System.out.println(a + " " + b + " " + c);
}
m++;
}
}
// Driver Code
public static void main(String args[])
{
int limit = 20;
pythagoreanTriplets(limit);
}
}
// This code is contributed by Manish.
Python
# Python3 program to generate pythagorean
# triplets smaller than a given limit
# Function to generate pythagorean
# triplets smaller than limit
def pythagoreanTriplets(limits) :
c, m = 0, 2
# Limiting c would limit
# all a, b and c
while c < limits :
# Now loop on n from 1 to m-1
for n in range(1, m) :
a = m * m - n * n
b = 2 * m * n
c = m * m + n * n
# if c is greater than
# limit then break it
if c > limits :
break
print(a, b, c)
m = m + 1
# Driver Code
if __name__ == '__main__' :
limit = 20
pythagoreanTriplets(limit)
# This code is contributed by Shrikant13.
C#
// C# program to generate pythagorean
// triplets smaller than a given limit
using System;
class GFG {
// Function to generate pythagorean
// triplets smaller than limit
static void pythagoreanTriplets(int limit)
{
// triplet: a^2 + b^2 = c^2
int a, b, c = 0;
// loop from 2 to max_limit
int m = 2;
// Limiting c would limit
// all a, b and c
while (c < limit) {
// now loop on j from 1 to i-1
for (int n = 1; n < m; ++n)
{
// Evaluate and print
// triplets using
// the relation between
// a, b and c
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
if (c > limit)
break;
Console.WriteLine(a + " "
+ b + " " + c);
}
m++;
}
}
// Driver Code
public static void Main()
{
int limit = 20;
pythagoreanTriplets(limit);
}
}
// This code is contributed by anuj_67.
JavaScript
<script>
// Javascript program to generate pythagorean
// triplets smaller than a given limit
// Function to generate pythagorean
// triplets smaller than limit
function pythagoreanTriplets(limit)
{
// Triplet: a^2 + b^2 = c^2
let a, b, c = 0;
// Loop from 2 to max_limit
let m = 2;
// Limiting c would limit
// all a, b and c
while (c < limit)
{
// Now loop on j from 1 to i-1
for(let n = 1; n < m; ++n)
{
// Evaluate and print
// triplets using
// the relation between
// a, b and c
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
if (c > limit)
break;
document.write(a + " " + b +
" " + c + "</br>");
}
m++;
}
}
// Driver code
let limit = 20;
pythagoreanTriplets(limit);
// This code is contributed by divyesh072019
</script>
PHP
<?php
// PHP program to generate pythagorean
// triplets smaller than a given limit
// Function to generate pythagorean
// triplets smaller than limit
function pythagoreanTriplets($limit)
{
// triplet: a^2 + b^2 = c^2
$a;
$b;
$c=0;
// loop from 2 to max_limit
$m = 2;
// Limiting c would limit
// all a, b and c
while ($c < $limit)
{
// now loop on j from 1 to i-1
for ($n = 1; $n < $m; ++$n)
{
// Evaluate and print
// triplets using the
// relation between a,
// b and c
$a = $m *$m - $n * $n;
$b = 2 * $m * $n;
$c = $m * $m + $n * $n;
if ($c > $limit)
break;
echo $a, " ", $b, " ", $c, "\n";
}
$m++;
}
}
// Driver Code
$limit = 20;
pythagoreanTriplets($limit);
// This code is contributed by ajit.
?>
Output3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
Time complexity of this approach is O(√n) where n is the given limit. We are iterating until c <= limit ,where c = m^2 + n^2. Thus the iteration will take place approximately sqrt(limit) times.
Auxiliary space: O(1) as it is using constant space for variables
References:
https://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem