How to resolve the algorithm Square but not cube step by step in the C programming language
How to resolve the algorithm Square but not cube step by step in the C programming language
Table of Contents
Problem Statement
Show the first 30 positive integers which are squares but not cubes of such integers. Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Square but not cube step by step in the C programming language
This C code finds and prints the squares of integers starting from 1 that are not perfect cubes. Here's how it works:
-
It includes the necessary header files,
<stdio.h>
for input and output, and<math.h>
for thecbrt
function to find cube roots. -
It defines three integer variables:
n
: The integer whose square is being considered.count
: Keeps track of the number of non-perfect squares found.sq
: Stores the square ofn
.cr
: Stores the integer cube root ofsq
.
-
It enters a
for
loop that continues untilcount
is less than 30, which means it will iterate until 30 non-perfect squares are found. -
Inside the loop:
- It calculates the square of
n
and stores it insq
. - It calculates the integer cube root of
sq
using(int)cbrt((double)sq)
and stores it incr
. - It checks if
cr * cr * cr
is not equal tosq
. This condition checks ifsq
is not a perfect cube. - If the condition is true, it means
sq
is not a perfect cube. It incrementscount
and printssq
usingprintf("%d\n", sq);
. - If the condition is false, it means
sq
is a perfect cube. It prints a message indicating thatsq
is both a square and a cube usingprintf("%d is square and cube\n", sq);
.
- It calculates the square of
-
The loop continues until
count
reaches 30, at which point it exits the loop and the program terminates.
Source code in the c programming language
#include <stdio.h>
#include <math.h>
int main() {
int n = 1, count = 0, sq, cr;
for ( ; count < 30; ++n) {
sq = n * n;
cr = (int)cbrt((double)sq);
if (cr * cr * cr != sq) {
count++;
printf("%d\n", sq);
}
else {
printf("%d is square and cube\n", sq);
}
}
return 0;
}
You may also check:How to resolve the algorithm Truncatable primes step by step in the Arturo programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the SNOBOL4 programming language
You may also check:How to resolve the algorithm Quine step by step in the Plain TeX programming language
You may also check:How to resolve the algorithm Ternary logic step by step in the Ruby programming language
You may also check:How to resolve the algorithm Null object step by step in the Go programming language