Count numbers upto N which are both perfect square and perfect cube in C++


We are given a number N. The goal is to count the numbers upto N that are perfect squares as well as perfect cubes. For example, 1, 64 are both perfect squares and perfect cubes.

We will use sqrt() to calculate square root and cbrt() to calculate cube root of a number.

Let’s understand with examples.

Input − N=100

Output − Count of numbers that are perfect squares and cubes − 2

Explanation − 1 and 64 are only numbers from 1 to 100 that are both perfect squares and cubes.

Input − N=5000

Output −Count of numbers that are perfect squares and cubes − 3

Explanation − 1, 64 and 4096 are only numbers from 1 to 5000 that are both perfect squares and cubes.

Approach used in the below program is as follows

  • We take an integer N.

  • Function getCount(int n) takes N and returns the count of numbers upto N that are both perfect squares and perfect cubes.

  • Take the initial count as 0.

  • Starting from i=1 to i=N, if floor(sqrt(i))==ceil(sqrt(i)) then i is a perfect square.

  • Now check if floor(cbrt(i))==ceil(cbrt(i)), if true i is also a perfect cube. Increment count.

  • At the end of loop return count as result.

Example

 Live Demo

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

Output

If we run the above code it will generate the following output −

Numbers upto N that are perfect squares and perfect cubes:2

Updated on: 31-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements