用 C++ 統計 1 到 N 之間既是完全平方數又是完全立方數的數字個數
給定一個數字 N。目標是統計 1 到 N 之間既是完全平方數又是完全立方數的數字個數。例如,1、64 既是完全平方數又是完全立方數。
我們將使用 sqrt() 計算數字的平方根,並使用 cbrt() 計算數字的立方根。
讓我們透過示例來理解。
輸入 - N=100
輸出 - 既是完全平方數又是完全立方數的數字個數 - 2
解釋 - 1 和 64 是 1 到 100 之間唯一既是完全平方數又是完全立方數的數字。
輸入 - N=5000
輸出 - 既是完全平方數又是完全立方數的數字個數 - 3
解釋 - 1、64 和 4096 是 1 到 5000 之間唯一既是完全平方數又是完全立方數的數字。
下面程式中使用的方案如下
我們取一個整數 N。
函式 getCount(int n) 獲取 N 並返回 1 到 N 之間既是完全平方數又是完全立方數的數字個數。
將初始計數設為 0。
從 i=1 到 i=N 開始,如果 floor(sqrt(i))==ceil(sqrt(i)),則 i 是一個完全平方數。
現在檢查 floor(cbrt(i))==ceil(cbrt(i)) 是否為真,如果為真,則 i 也是一個完全立方數。遞增計數。
在迴圈結束時,返回計數作為結果。
示例
#include <bits/stdc++.h> #include <math.h> using namespace std; int getCount(int n){ int count=0; for(int i=1;i<=n;i++){ if(floor(sqrt(i))==ceil(sqrt(i))){ if(floor(cbrt(i))==ceil(cbrt(i))){ count++; //cout<<i<<" "; } } } return count; } int main(){ int N=100; cout<<endl<<"Numbers upto N that are perfect squares and perfect cubes:"<<getCount(N); return 0; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
Numbers upto N that are perfect squares and perfect cubes:2
廣告