小于 n 的无立方数
无立方数是指没有立方数因子的数。
立方数因子是指一个整数,它是某个整数的立方,并且能够整除该数。
例如,8 是 16 的一个立方数因子,因为 8 是 2 的立方 (2*2*2 = 8),并且 8 可以整除 16,余数为零。
因此,8 和 16 都不是无立方数。
问题陈述
找到所有小于给定数字 n 的无立方数。
示例
Let's understand the problem with an example. Let n = 15, Thus, we have to find all the numbers less than 15 that are cube-free. The solution will be: 2,3,4,5,6,7,9,10,11,12,13,14. For another example, Let n = 20. The numbers are 2,3,4,5,6,7,9,10,11,12,13,14,15,17,18,19.
解释
注意列表中没有 1、8 和 16。因为 1 和 8 本身就是立方数,而 16 是 8 的倍数。
解决这个问题有两种方法。
方法 1:暴力法
暴力法如下:
遍历所有小于 n 的数字。
对于每个数字,遍历其所有因子。
如果数字的任何因子是立方数,则该数字不是无立方数。
否则,如果数字的任何因子都不是立方数,则它是一个无立方数。
打印该数字。
示例
此方法的程序如下:
下面是一个 C++ 程序,用于打印所有小于给定数字 n 的无立方数。
#include<iostream>
using namespace std;
// This function returns true if the number is cube free.
// Else it returns false.
bool is_cube_free(int n){
if(n==1){
return false;
}
//Traverse through all the cubes lesser than n
for(int i=2;i*i*i<=n ;i++){
//If a cube divides n completely, then return false.
if(n%(i*i*i) == 0){
return false;
}
}
return true;
}
int main(){
int n = 17;
cout<<"The cube free numbers smaller than 17 are:"<<endl;
//Traverse all the numbers less than n
for(int i=1;i<n;i++){
//If the number is cube free, then print it.
if(is_cube_free(i)){
cout<<i<<" ";
}
}
}
输出
The cube free numbers smaller than 17 are: 2 3 4 5 6 7 9 10 11 12 13 14 15
方法 2:埃拉托色尼筛法
解决此问题的有效方案是使用埃拉托色尼筛法的概念。
它用于查找小于给定限制的所有素数。在这里,我们将筛选出不是无立方数的数字以获得我们的解决方案。
方法如下:
创建一个大小为 n 的布尔列表。
将所有数字标记为真。这意味着我们目前已将所有数字标记为无立方数。
遍历所有小于 n 的可能的立方数。
遍历小于 n 的立方数的所有倍数。
在列表中将所有这些倍数标记为假。这些数字不是无立方数。
遍历列表。打印列表中仍然为真的数字。
输出将包含所有小于 n 的无立方数。
示例
此方法的程序如下:
下面是一个 C++ 程序,使用埃拉托色尼筛法打印所有小于给定数字 n 的无立方数。
#include<iostream>
#include<vector>
using namespace std;
//Find which numbers are cube free and mark others as false in the vector.
void find_cube_free(vector<bool>&v, int n){
//Traverse through all the numbers whose cubes are lesser than n
for(int i=2;i*i*i<n;i++){
//If i isn't cube free, it's multiples would have been marked false too
if(v[i]==true){
//Mark all the multiples of the cube of i as not cube free.
for(int j=1;i*i*i*j<n;j++){
v[i*i*i*j] = false;
}
}
}
}
int main(){
int n = 15;
//Vector to store which numbers are cube free
//Initially, we set all the numbers as cube free
vector<bool>v(n,true);
find_cube_free(v,n);
cout<<"The cube free numbers smaller than are:"<<endl;
//Traverse the vector and print the cube free numbers
for(int i=2;i<n;i++){
if(v[i]==true){
cout<<i<<" ";
}
}
}
输出
The cube free numbers smaller than are: 2 3 4 5 6 7 9 10 11 12 13 14
本文解决了查找小于 n 的无立方数的问题。我们看到了两种方法:一种是暴力法,另一种是使用埃拉托色尼筛法的有效方法。
两种方法都提供了 C++ 程序。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP