How to resolve the algorithm Square but not cube step by step in the C programming language

Published on 7 June 2024 03:52 AM
#C

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 the cbrt 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 of n.
    • cr: Stores the integer cube root of sq.
  • It enters a for loop that continues until count 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 in sq.
    • It calculates the integer cube root of sq using (int)cbrt((double)sq) and stores it in cr.
    • It checks if cr * cr * cr is not equal to sq. This condition checks if sq is not a perfect cube.
    • If the condition is true, it means sq is not a perfect cube. It increments count and prints sq using printf("%d\n", sq);.
    • If the condition is false, it means sq is a perfect cube. It prints a message indicating that sq is both a square and a cube using printf("%d is square and cube\n", sq);.
  • 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