Open In App

Find all Ramanujan Numbers that can be formed by numbers upto L

Given a positive integer L, the task is to find all the Ramanujan Numbers that can be generated by any set of quadruples (a, b, c, d), where 0 < a, b, c, d ? L.

Ramanujan Numbers are the numbers that can be expressed as sum of two cubes in two different ways. 
Therefore, Ramanujan Number (N) = a3 + b3 = c3 + d3
 



Examples:

Input: L = 20
Output: 1729, 4104
Explanation:
The number 1729 can be expressed as 123 + 13 and 103 + 93.
The number 4104 can be expressed as 163 + 23 and 153 + 93.



Input: L = 30
Output: 1729, 4104, 13832, 20683

Naive Approach: The simplest approach is to check for all combination of quadruples (a, b, c, d) from the range [1, L] consisting of distinct elements that satisfy the equation a3 + b3 = c3 + d3. For elements found to be satisfying the conditions, store the Ramanujan Numbers as a3 + b3. Finally, after checking for all possible combinations, print all the stored numbers.

Below is the implementation of the above approach:




// CPP program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to find Ramanujan numbers
// made up of cubes of numbers up to L
map<int,vector<int>> ramanujan_On4(int limit)
{
    map<int,vector<int>> dictionary;
 
    // Generate all quadruples a, b, c, d
    // of integers from the range [1, L]
    for(int a = 0; a < limit; a++)
    {
        for(int b = 0; b < limit; b++)
        {
            for(int c = 0; c < limit; c++)
            {
               for(int d = 0; d < limit; d++)
               {
 
                    // Condition // 2:
                    // a, b, c, d are not equal
                    if ((a != b) and (a != c) and (a != d)
                        and (b != c) and (b != d)
                            and (c != d)){
 
                        int x = pow(a, 3) + pow(b, 3);
                        int y = pow(c, 3) + pow(d, 3);
                        if ((x) == (y))
                        {
                            int number = pow(a, 3) + pow(b, 3);
                            dictionary[number] = {a, b, c, d};
                        }
                    }
            }
        }
    }
}
 
    // Return all the possible number
    return dictionary;
}
 
// Driver Code
int main()
{
    
// Given range L
int L = 30;
map<int, vector<int>> ra1_dict = ramanujan_On4(L);
 
// Print all the generated numbers
for(auto x:ra1_dict)
{
    cout << x.first << ": (";
   
   // sort(x.second.begin(),x.second.end());
    for(int i = x.second.size() - 1; i >= 0; i--)
    {
        if(i == 0)
          cout << x.second[i] << ")";
        else
         cout << x.second[i] << ", ";   
    }
    cout << endl;
}
}
 
// This code is contributed by SURENDRA_GANGWAR.




// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
static Map<Integer, List<Integer>> ra1_dict; 
 
// Function to find Ramanujan numbers
// made up of cubes of numbers up to L
static void ramanujan_On4(int limit)
{
     
    // Generate all quadruples a, b, c, d
    // of integers from the range [1, L]
    for(int a = 0; a < limit; a++)
    {
        for(int b = 0; b < limit; b++)
        {
            for(int c = 0; c < limit; c++)
            {
               for(int d = 0; d < limit; d++)
               {
 
                    // Condition // 2:
                    // a, b, c, d are not equal
                    if ((a != b) && (a != c) && (a != d) &&
                        (b != c) && (b != d) && (c != d))
                    {
                        int x = (int)Math.pow(a, 3) +
                                (int) Math.pow(b, 3);
                        int y = (int)Math.pow(c, 3) +
                                (int) Math.pow(d, 3);
                        if ((x) == (y))
                        {
                            int number = (int)Math.pow(a, 3) +
                                         (int) Math.pow(b, 3);
                            ra1_dict.put(number, new ArrayList<>(
                                Arrays.asList(a, b, c, d)));
                        }
                    }
                }
            }
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given range L
    int L = 30;
     
    ra1_dict = new HashMap<>();
     
    ramanujan_On4(L);
     
    // Print all the generated numbers
    for(Map.Entry<Integer,
             List<Integer>> x: ra1_dict.entrySet())
    {
        System.out.print(x.getKey() + ": (");
         
        // sort(x.second.begin(),x.second.end());
        for(int i = x.getValue().size() - 1; i >= 0; i--)
        {
            if (i == 0)
                System.out.print(x.getValue().get(i) + ")");
            else
                System.out.print(x.getValue().get(i) + ", ");   
        }
        System.out.println();
    }
}
}
 
// This code is contributed by offbeat




# Python program for the above approach
import time
 
# Function to find Ramanujan numbers
# made up of cubes of numbers up to L
def ramanujan_On4(limit):
    dictionary = dict()
 
    # Generate all quadruples a, b, c, d
    # of integers from the range [1, L]
    for a in range(0, limit):
        for b in range(0, limit):
            for c in range(0, limit):
                for d in range(0, limit):
 
                    # Condition # 2:
                    # a, b, c, d are not equal
                    if ((a != b) and (a != c) and (a != d)
                        and (b != c) and (b != d)
                            and (c != d)):
 
                        x = a ** 3 + b ** 3
                        y = c ** 3 + d ** 3
                        if (x) == (y):
                            number = a ** 3 + b ** 3
                            dictionary[number] = a, b, c, d
 
    # Return all the possible number
    return dictionary
 
 
# Driver Code
 
# Given range L
L = 30
ra1_dict = ramanujan_On4(L)
 
# Print all the generated numbers
for i in sorted(ra1_dict):
    print(f'{i}: {ra1_dict[i]}', end ='\n')




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  static Dictionary<int, List<int>> ra1_dict;
 
  // Function to find Ramanujan numbers
  // made up of cubes of numbers up to limit
  static void Ramanujan_On4(int limit) {
 
    // Generate all quadruples a, b, c, d
    // of integers from the range [1, limit]
    for (int a = 0; a < limit; a++) {
      for (int b = 0; b < limit; b++) {
        for (int c = 0; c < limit; c++) {
          for (int d = 0; d < limit; d++) {
 
            // Condition 2:
            // a, b, c, d are not equal
            if ((a != b) && (a != c) && (a != d) &&
                (b != c) && (b != d) && (c != d)) {
              int x = (int)Math.Pow(a, 3) +
                (int)Math.Pow(b, 3);
              int y = (int)Math.Pow(c, 3) +
                (int)Math.Pow(d, 3);
              if (x == y) {
                int number = (int)Math.Pow(a, 3) +
                  (int)Math.Pow(b, 3);
                ra1_dict[number] = new List<int>{a, b, c, d};
              }
            }
          }
        }
      }
    }
  }
 
  // Driver code
  static void Main(string[] args) {
 
    // Given range L
    int L = 30;
 
    ra1_dict = new Dictionary<int, List<int>>();
 
    // Function call
    Ramanujan_On4(L);
 
    // Print all the generated numbers
    foreach (var x in ra1_dict) {
      Console.Write(x.Key + ": (");
 
      // sort(x.second.begin(),x.second.end());
      for (int i = x.Value.Count - 1; i >= 0; i--) {
        if (i == 0)
          Console.Write(x.Value[i] + ")");
        else
          Console.Write(x.Value[i] + ", ");
      }
      Console.WriteLine();
    }
  }
}
 
// This code is contributed by phasing17




<script>
 
      // JavaScript program for the above approach
       
       // Function to find Ramanujan numbers
      // made up of cubes of numbers up to L
      function ramanujan_On4(limit) {
        var dictionary = {};
 
        // Generate all quadruples a, b, c, d
        // of integers from the range [1, L]
        for (var a = 0; a < limit; a++) {
          for (var b = 0; b < limit; b++) {
            for (var c = 0; c < limit; c++) {
              for (var d = 0; d < limit; d++) {
                // Condition // 2:
                // a, b, c, d are not equal
                if (
                  a !== b &&
                  a !== c &&
                  a !== d &&
                  b !== c &&
                  b !== d &&
                  c !== d
                ) {
                  var x = Math.pow(a, 3) + Math.pow(b, 3);
                  var y = Math.pow(c, 3) + Math.pow(d, 3);
                  if (x == y) {
                   var number =
                   Math.pow(a, 3) + Math.pow(b, 3);
                    
                   dictionary[number] =
                   [" " + a, " " + b, " " + c, d];
                  }
                }
              }
            }
          }
        }
        return dictionary;
      }
 
      // Driver code
      // Given range L
      var L = 30;
 
      var ra1_dict = ramanujan_On4(L);
 
      var temp = Object.keys(ra1_dict)
        .sort()
        .reduce((r, k) => ((r[k] = ra1_dict[k]), r), {});
      // Print all the generated numbers
      for (const [key, value] of Object.entries(temp)) {
        document.write(key + ": (" + value.reverse() + ")" +
        "<br>");
      }
       
</script>

Output: 
1729: (9, 10, 1, 12)
4104: (9, 15, 2, 16)
13832: (18, 20, 2, 24)
20683: (19, 24, 10, 27)

 

Time Complexity: O(L4)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by using Hashing. Follow the steps below to solve the problem:

Below is the implementation of the above approach:




#include <bits/stdc++.h>
using namespace std;
 
map<int, vector<int> > ramanujan_On2(int limit)
{
    // Stores the cubes from 1 to L
    int cubes[limit + 1];
    for (int i = 0; i <= limit; i++) {
        cubes[i] = i * i * i;
    }
 
    // Stores the sum of pairs of cubes
    map<int, vector<int> > dict_sum_pairs;
 
    // Stores the Ramanujan Numbers
    map<int, vector<int> > dict_ramnujan_nums;
 
    // Generate all pairs (a, b)
    // from the range [0, L]
    for (int a = 0; a <= limit; a++) {
        for (int b = a + 1; b <= limit; b++) {
            int a3 = cubes[a];
            int b3 = cubes[b];
 
            // Find the sum of pairs
            int sum_pairs = a3 + b3;
 
            // Add to Map
            if (dict_sum_pairs.count(sum_pairs)) {
 
                // If the current sum_pair is already in
                // the sum_pair Map, then store store
                // all numbers in ramnujan_no map
                int c = dict_sum_pairs[sum_pairs][0];
                int d = dict_sum_pairs[sum_pairs][1];
                dict_ramnujan_nums[sum_pairs]
                    = { a, b, c, d };
            }
            else {
 
                // otherwise add in sum_pair map
                dict_sum_pairs[sum_pairs] = { a, b };
            }
        }
    }
    // Return possible ramanujan numbers
    return dict_ramnujan_nums;
}
 
int main()
{
    // Given range L
    int L = 30;
 
    map<int, vector<int> > r_dict
        = ramanujan_On2(L);
 
    // Print all the generated numbers
    for (auto& e : r_dict) {
 
        cout << e.first << ": (";
 
        for (int i = 0; i < e.second.size(); i++) {
            if (i == e.second.size() - 1)
                cout << e.second[i] << ")";
            else
                cout << e.second[i] << ", ";
        }
        cout << endl;
    }
    return 0;
}




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function to find Ramanujan numbers
  static HashMap<Integer, ArrayList<Integer> >
    ramanujan_On2(int limit)
  {
     
    // Stores the cubes from 1 to L
    int[] cubes = new int[limit + 1];
    for (int i = 0; i <= limit; i++) {
      cubes[i] = i * i * i;
    }
     
    // Stores the sum of pairs of cubes
    HashMap<Integer, ArrayList<Integer> > dict_sum_pairs
      = new HashMap<>();
 
    // Stores the Ramanujan Numbers
    HashMap<Integer, ArrayList<Integer> >
      dict_ramnujan_nums = new HashMap<>();
 
    // Generate all pairs (a, b)
    // from the range [0, L]
    for (int a = 0; a <= limit; a++) {
      for (int b = a + 1; b <= limit; b++) {
        int a3 = cubes[a];
        int b3 = cubes[b];
         
        // Find the sum of pairs
        int sum_pairs = a3 + b3;
         
        // Add to Map
        if (dict_sum_pairs.containsKey(sum_pairs))
        {
           
          // If the current sum_pair is already in
          // the sum_pair Map, then store store
          // all numbers in ramnujan_no map
          int c
            = dict_sum_pairs.get(sum_pairs).get(
            0);
          int d
            = dict_sum_pairs.get(sum_pairs).get(
            1);
          dict_ramnujan_nums.put(
            sum_pairs,
            new ArrayList<>(
              Arrays.asList(a, b, c, d)));
        }
        else
        {
           
          // otherwise add in sum_pair map
          dict_sum_pairs.put(
            sum_pairs,
            new ArrayList<>(
              Arrays.asList(a, b)));
        }
      }
    }
    // Return possible ramanujan numbers
    return dict_ramnujan_nums;
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // Given range L
    int L = 30;
 
    HashMap<Integer, ArrayList<Integer> > r_dict
      = ramanujan_On2(L);
 
    // Print all the generated numbers
    for (Map.Entry<Integer, ArrayList<Integer> > e :
         (Iterable<
          Map.Entry<Integer, ArrayList<Integer> > >)
         r_dict.entrySet()
         .stream()
         .sorted(
           Map.Entry
           .comparingByKey())::iterator) {
 
      System.out.print(e.getKey() + ": (");
 
      for (int i = 0; i <= e.getValue().size() - 1;
           i++) {
        if (i == e.getValue().size() - 1)
          System.out.print(e.getValue().get(i)
                           + ")");
        else
          System.out.print(e.getValue().get(i)
                           + ", ");
      }
      System.out.println();
    }
  }
}
 
// This code is contributed by Karandeep1234




# Python program for the above approach
from array import *
import time
 
# Function to find Ramanujan numbers
# made up of cubes of numbers up to L
def ramanujan_On2(limit):
    cubes = array('i', [])
 
    # Stores the sum of pairs of cubes
    dict_sum_pairs = dict()
 
    # Stores the Ramanujan Numbers
    dict_ramnujan_nums = dict()
    sum_pairs = 0
 
    # Stores the cubes from 1 to L
    for i in range(0, limit):
        cubes.append(i ** 3)
      
    # Generate all pairs (a, b)
    # from the range [0, L]
    for a in range(0, limit):
        for b in range(a + 1, limit):
            a3, b3 = cubes[a], cubes[b]
 
            # Find the sum of pairs
            sum_pairs = a3 + b3
 
            # Append to dictionary
            if sum_pairs in dict_sum_pairs:
 
                # If the current sum is in
                # the dictionary, then store
                # the current number
                c, d = dict_sum_pairs.get(sum_pairs)
                dict_ramnujan_nums[sum_pairs] = a, b, c, d
 
            # Otherwise append the current
            # sum pairs to the sum pairs
            # dictionary
            else:
                dict_sum_pairs[sum_pairs] = a, b
 
        # Return the possible Ramanujan
    # Numbers
    return dict_ramnujan_nums
 
 
# Driver Code
 
# Given range L
L = 30
r_dict = ramanujan_On2(L)
 
# Print all the numbers
for d in sorted(r_dict):
    print(f'{d}: {r_dict[d]}', end ='\n')




// C# program for the above approach
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG {
 
  // Function to find Ramanujan numbers
  static Dictionary<int, List<int> >
    Ramanujan_On2(int limit)
  {
 
    // Stores the cubes from 1 to L
    int[] cubes = new int[limit + 1];
    for (int i = 0; i <= limit; i++) {
      cubes[i] = i * i * i;
    }
 
    // Stores the sum of pairs of cubes
    Dictionary<int, List<int> > dict_sum_pairs
      = new Dictionary<int, List<int> >();
 
    // Stores the Ramanujan Numbers
    Dictionary<int, List<int> > dict_ramanujan_nums
      = new Dictionary<int, List<int> >();
 
    // Generate all pairs (a, b)
    // from the range [0, L]
    for (int a = 0; a <= limit; a++) {
      for (int b = a + 1; b <= limit; b++) {
        int a3 = cubes[a];
        int b3 = cubes[b];
 
        // Find the sum of pairs
        int sum_pairs = a3 + b3;
 
        // Add to Map
        if (dict_sum_pairs.ContainsKey(sum_pairs)) {
 
          // If the current sum_pair is already in
          // the sum_pair Map, then store store
          // all numbers in ramnujan_no map
          int c = dict_sum_pairs[sum_pairs][0];
          int d = dict_sum_pairs[sum_pairs][1];
          dict_ramanujan_nums[sum_pairs]
            = new List<int>(
            new int[] { a, b, c, d });
        }
        else {
 
          // otherwise add in sum_pair map
          dict_sum_pairs[sum_pairs]
            = new List<int>(new int[] { a, b });
        }
      }
    }
    // Return possible ramanujan numbers
    return dict_ramanujan_nums;
  }
 
  // Driver code
  static void Main(string[] args)
  {
 
    // Given range L
    int L = 30;
 
    Dictionary<int, List<int> > r_dict
      = Ramanujan_On2(L);
 
    // Print all the generated numbers
    foreach(KeyValuePair<int, List<int> > e in
            r_dict.OrderBy(key => key.Key))
    {
 
      Console.Write(e.Key + ": (");
 
      for (int i = 0; i <= e.Value.Count - 1; i++) {
        if (i == e.Value.Count - 1)
          Console.Write(e.Value[i] + ")");
        else
          Console.Write(e.Value[i] + ", ");
      }
      Console.WriteLine();
    }
  }
}
 
// This code is contributed by phasing17




// JavaScript equivalent of the Python code
 
// Function to find Ramanujan numbers
// made up of cubes of numbers up to L
function ramanujan_On2(limit) {
  let cubes = [];
 
  // Stores the sum of pairs of cubes
  let dict_sum_pairs = {};
 
  // Stores the Ramanujan Numbers
  let dict_ramanujan_nums = {};
  let sum_pairs = 0;
 
  // Stores the cubes from 1 to L
  for (let i = 0; i < limit; i++) {
    cubes.push(i ** 3);
  }
 
  // Generate all pairs (a, b)
  // from the range [0, L]
  for (let a = 0; a < limit; a++) {
    for (let b = a + 1; b < limit; b++) {
      let a3 = cubes[a];
      let b3 = cubes[b];
 
      // Find the sum of pairs
      sum_pairs = a3 + b3;
 
      // Append to dictionary
      if (dict_sum_pairs[sum_pairs]) {
        // If the current sum is in
        // the dictionary, then store
        // the current number
        let [c, d] = dict_sum_pairs[sum_pairs];
        dict_ramanujan_nums[sum_pairs] = [a, b, c, d];
      } else {
        // Otherwise append the current
        // sum pairs to the sum pairs
        // dictionary
        dict_sum_pairs[sum_pairs] = [a, b];
      }
    }
  }
 
  // Return the possible Ramanujan
  // Numbers
  return dict_ramanujan_nums;
}
 
// Driver Code
 
// Given range L
const L = 30;
const r_dict = ramanujan_On2(L);
 
// Print all the numbers
for (let d in r_dict) {
  console.log(`${d}: ${r_dict[d]}`);
}
 
// This code is contributed by phasing17.

Output: 
1729: (9, 10, 1, 12)
4104: (9, 15, 2, 16)
13832: (18, 20, 2, 24)
20683: (19, 24, 10, 27)

 

Time Complexity: O(L2)
Auxiliary Space: O(L2)


Article Tags :