C Programming: Perfect square
C Programming Mathematics: Exercise-29 with Solution
Write a C programming to get the smallest number of square numbers that add up to an integer n.
In mathematics, a perfect square is a number that can be expressed as either the product of an integer by itself or as the second exponent of an integer..
Sample Data:
14 = 32 + 22 + 12
Output – 3
15 = 32 + 22 + 12 + 12
Output - 4
16 = 42
Output – 1
17 = 42 + 12
Output – 2
Sample Solution:
C Code:
#include <stdio.h>
#include <stdlib.h>
#include <mem.h>
int test(int n) {
int * nums = (int * ) malloc((n + 1) * sizeof(int));
memset(nums, 10000, (n + 1) * sizeof(int));
nums[0] = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j * j <= i; j++)
nums[i] = nums[i] < nums[i - j * j] + 1 ? nums[i] : nums[i - j * j] + 1;
return nums[n];
}
int main(void) {
int n = 14;
printf("%d number of square numbers equal to %d", test(n), n);
n = 15;
printf("\n%d number of square numbers equal to %d", test(n), n);
n = 16;
printf("\n%d number of square numbers equal to %d", test(n), n);
n = 17;
printf("\n%d number of square numbers equal to %d", test(n), n);
}
Sample Output:
3 number of square numbers equal to 14 4 number of square numbers equal to 15 1 number of square numbers equal to 16 2 number of square numbers equal to 17
Flowchart:

C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Find angle between given hour and minute hands.
Next: Count all the numbers with unique digits in a range.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join