Cube Free Numbers smaller than n | Efficient Java Program to print all cube free numbers smaller than or equal to n . ; Initialize all numbers as not cube free ; Traverse through all possible cube roots ; If i itself is cube free ; Mark all multiples of i as not cube free ; Print all cube free numbers ; Driver code
class GFG { public static void printCubeFree ( int n ) { boolean [ ] cubFree = new boolean [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) cubFree [ i ] = true ; for ( int i = 2 ; i * i * i <= n ; i ++ ) { if ( cubFree [ i ] ) { for ( int multiple = 1 ; i * i * i * multiple <= n ; multiple ++ ) { cubFree [ i * i * i * multiple ] = false ; } } } for ( int i = 2 ; i <= n ; i ++ ) { if ( cubFree [ i ] == true ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { printCubeFree ( 20 ) ; } }