  A number square free number whose none of any divisor is a cubic number (a number which is cube of an integer). Given an integer n, find all cube free than or equal to n.

Examples:

Input :  n =
Output : 2 3 4 5 6 7 9
Note that only 1 and 8 are missing.

Input : 20
Output : 2 3 4 5 6 7 9  11  13 14
15 17 18 19 20

A simple solution is to traverse through all numbers from 1 to n. For every number check if it is cube free or not. If yes, then print it.

// Simple C++ Program to print all cube free
// numbers smaller than or equal to n.
#include <bits/stdc++.h>
using namespace std;

// Returns true if n is a cube free
// number, else returns false.
bool isCubeFree(int n)
{
if (n == 1)
return false;

// check for all possible divisible cubes
for (int i = 2; i * i * i <= n; i++)
if (n % (i * i * i) == 0)
return false;

return true;
}

// Print all cube free numbers smaller
// than n.
void printCubeFree(int n)
{
for (int i = 2; i <= n; i++)
if (isCubeFree(i))
cout << i << " ";
}

/* Driver program to test above function */
int main()
{
int n = 20;
printCubeFree(n);
return 0;
}
Output:
2 3 4 5 6 7 9 10 11 12 13 14 15 17 18 19 20

An efficient solution is to use Sieve of Eratosthenes like technique, to wash out the non cube free numbers. Here we will create boolean sieve array and initialize it with true values. Now we will start iterating a variable ‘div’ from 2, and start marking multiples of cube of div as false as those will be the non cube free numbers. Then after this the
elements left with value true will be the cube free numbers.

// Efficient Java Program to print all cube free
// numbers smaller than or equal to n.
class GFG {

public static void printCubeFree(int n)
{
// Initialize all numbers as not cube free
boolean[] cubFree = new boolean[n + 1];
for (int i = 0; i <= n; i++)
cubFree[i] = true;

// Traverse through all possible cube roots
for (int i = 2; i * i * i <= n; i++) {

// If i itself is cube free
if (cubFree[i]) {

// Mark all multiples of i as not cube free
for (int multiple = 1; i * i * i * multiple <= n;
multiple++) {

cubFree[i * i * i * multiple] = false;
}
}
}

// Print all cube free numbers
for (int i = 2; i <= n; i++) {
if (cubFree[i] == true)
System.out.print(i + " ");
}
}

public static void main(String[] args)
{
printCubeFree(20);
}
}
Output:
2 3 4 5 6 7 9 10 11 12 13 14 15 17 18 19 20 If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

SHARE
Previous articleConnected screens are revolutionizing payments