
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Perfect Squares in C++
Suppose we have a positive integer n, find the least number of perfect square numbers whose sum is n. So if the number is 13, then the output is 2, as the numbers are 13 = 9 + 4
To solve this, we will follow these steps −
- create one table for dynamic programming, of length n + 1, and fill it with infinity
- dp[0] := 0
- for i := 1, when i*i <= n
- x = i * i
- for j := x to n
- dp[j] := minimum of dp[j] and 1 + dp[j – x]
- return dp[n]
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; #define INF 1e9 class Solution { public: int numSquares(int n) { vector < int > dp(n+1,INF); dp[0] = 0; for(int i =1;i*i<=n;i++){ int x = i*i; for(int j = x;j<=n;j++){ dp[j] = min(dp[j],1+dp[j-x]); } } return dp[n]; } }; main(){ Solution ob; cout << (ob.numSquares(147)); }
Input
147
Output
3
- Related Articles
- Python program to filter perfect squares in a given series
- Is a number sum of two perfect squares in JavaScript
- Smallest number of perfect squares that sums up to n in JavaScript
- Which of the following perfect squares are squares of even numbers?25, 64, 100, 169, 256, 289, 961, 1296, 6561, 8100.Which of the following perfect squares are squares of odd numbers?36, 49, 64, 81, 100, 121, 169, 484, 625, 900, 1296, 1681.
- Program to count number of perfect squares are added up to form a number in C++
- Find the least numbers which must be subtracted from the following number make them perfect squares: $16160$.
- The following numbers are not perfect squares. Give reason:(i) 1547(ii) 45743(iii) 8948(iv) 333333.
- Show that the following numbers are not perfect squares:(i) 9327(ii) 4058(iii) 22453(iv) 743522.
- Which of the following numbers are perfect squares ?11, 12, 16, 32, 36, 50, 64, 79, 81, 111, 121
- Which of the following numbers are perfect squares ?(i) 484(ii) 625(iii) 576(iv) 941(v) 961(vi) 2500.
- Word Squares in C++
- Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10
- Present Perfect vs. Present Perfect Continuous Tense
- Perfect Rectangle in C++
- Perfect Number in C++

Advertisements