Check if a number can be represented as sum of two positive perfect cubes | Java program for the above approach ; Function to check if N can be represented as sum of two perfect cubes or not ; Stores the perfect cubes of first N natural numbers ; Traverse the map ; Stores first number ; Stores second number ; Search the pair for the first number to obtain sum N from the Map ; If N cannot be represented as sum of two positive perfect cubes ; Driver code ; Function call to check if N can be represented as sum of two perfect cubes or not
import java . util . * ; class GFG { public static void sumOfTwoPerfectCubes ( int N ) { HashMap < Integer , Integer > cubes = new HashMap < > ( ) ; for ( int i = 1 ; i * i * i <= N ; i ++ ) cubes . put ( ( i * i * i ) , i ) ; Iterator < Map . Entry < Integer , Integer > > itr = cubes . entrySet ( ) . iterator ( ) ; while ( itr . hasNext ( ) ) { Map . Entry < Integer , Integer > entry = itr . next ( ) ; int firstNumber = entry . getKey ( ) ; int secondNumber = N - entry . getKey ( ) ; if ( cubes . containsKey ( secondNumber ) ) { System . out . println ( " True " ) ; return ; } } System . out . println ( " False " ) ; } public static void main ( String [ ] args ) { int N = 28 ; sumOfTwoPerfectCubes ( N ) ; } }