Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวนที่เป็นกำลังสองและกำลังสามพร้อมกันถึง N ใน C++

ได้รับจำนวน N ต้องการนับจำนวนเต็มบวก ≤ N ที่เป็นกำลังสองและกำลังสามพร้อมกัน เช่น 1 (1²=1³), 64 (8²=4³)

ข้อสังเกต

ตัวเลขที่เป็นทั้งกำลังสองและกำลังสาม คือกำลังหก (sixth power): 1⁶=1, 2⁶=64, 3⁶=729, 4⁶=4096...

ตัวอย่าง

อินพุต: N = 100

เอาต์พุต: 2 (1 และ 64)

อินพุต: N = 5000

เอาต์พุต: 3 (1, 64, 4096)

แนวทาง

  • วนลูป i จาก 1 ถึง N
  • ตรวจสอบ floor(sqrt(i)) == ceil(sqrt(i)) (เป็นกำลังสอง)
  • และ floor(cbrt(i)) == ceil(cbrt(i)) (เป็นกำลังสาม)
  • ถ้าทั้งสองจริง เพิ่มตัวนับ

ตัวอย่างโค้ด C++

#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++;
            }
        }
    }
    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