- Related Questions & Answers
- Print n numbers such that their sum is a perfect square
- Check Perfect Square or Not
- Count the nodes whose weight is a perfect square in C++
- Check for perfect square in JavaScript
- Count all triplets whose sum is equal to a perfect cube in C++
- Count square and non-square numbers before n in C++
- Finding perfect numbers in JavaScript
- Count of pairs in an array whose sum is a perfect square in C++
- Perfect Squares in C++
- Perfect Number in C++
- Perfect Rectangle in C++
- Check if a number is perfect square without finding square root in C++
- Program to count number of permutations where sum of adjacent pairs are perfect square in Python
- Check if given number is perfect square in Python
- C program to add all perfect square elements in an array.

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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.

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

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

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

Advertisements