Skip to content

Instantly share code, notes, and snippets.

@yclim95
Created April 22, 2022 12:33
Show Gist options
  • Save yclim95/921e960b6ff83e876bf561f63c4841f1 to your computer and use it in GitHub Desktop.
Save yclim95/921e960b6ff83e876bf561f63c4841f1 to your computer and use it in GitHub Desktop.
To square(root) or not to square(root)

To square(root) or not to square(root)

Write a method, that will get an integer array as parameter and will process every number from this array.

Return a new array with processing every number of the input-array like this:

If the number has an integer square root, take this, otherwise square the number.

Example
[4,3,9,7,2,1] -> [2,9,3,49,4,1]
Notes
The input array will always contain only positive numbers, and will never be empty or null.
#include <math.h>

int isPerfectSquare(int number)
{
    int iNum;
    float fNum;
 
    fNum=sqrt((double)number);
    iNum=fNum;
 
    if(iNum==fNum)
        return 1;
    else
        return 0;
}

int* squareOrSquareRoot(int* array, int length)
{
  int c;
  c = 0;
  if (length > 0)
  {
    while (c < length)
    {
      if (isPerfectSquare(array[c]))
        array[c] = sqrt(array[c]);
      else
        array[c] *= array[c];
      c++;
    }
  } 
  return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment