- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to count number of perfect squares are added up to form a number in C++
Suppose we have a positive number n, we have to find the least number of perfect square numbers whose sum is same as n. So if the number is 10, then the output is 2, as the numbers are 10 = 9 + 1.
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 solve(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.solve(10); }
Input
10
Output
2
- Related Articles
- Smallest number of perfect squares that sums up to n in JavaScript
- Is a number sum of two perfect squares in JavaScript
- Program to count number of permutations where sum of adjacent pairs are perfect square in Python
- Count number of squares in a rectangle in C++
- Count all perfect divisors of a number in C++
- Python Program to Check if a Number is a Perfect Number
- Golang Program to Check if a Number is a Perfect Number
- Program to find number of squares in a chessboard in C++
- Golang Program to Count the Number of Digits in a Number
- Python program to filter perfect squares in a given series
- What least number must be added to 81180 to make it a perfect square?
- 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
- C++ program to count number of minutes needed to increase stick length to form a triangle
- C Program to check Plus Perfect Number
- Java Program to Find The Perfect Number

Advertisements