Checking if number is square root

F

F Tom

Guest
As the title says, how do you check if some given number is a square root of some other number?
 

TsukaYuriko

šŸŒ 
Forum Staff
Moderator
There's a sqrt function. Calculate the square root of a number using that, compare it to some other number and check if they're equal.
 
F

F Tom

Guest
There's a sqrt function. Calculate the square root of a number using that, compare it to some other number and check if they're equal.
I am creating a kind of crafting system where player/user can specify the size of the crafting field. The crafting field must be 3x3, 4x4 etc. It can't be for example 2x5. So the program gets the number of cells and it should check if dimensions are valid. It can be any number (in some normal ranges, not some crazy ones) such as 9, 36, 100 etc.
 
H

Husi012

Guest
My solution would be that:
Code:
var sr = sqrt(yourNumber)
if(sr == floor(sr))
//do something
 
A

Aura

Guest
The method suggested by @Husi012 isn't going to help unless you want only perfect squares to be chosen. For instance, it won't work for 3(x3) which you want to allow.

I'd personally go with setting the limit myself and clamping the size if it exceeds that limit.

Code:
cra_w = clamp(cra_w, min_w, max_w);
cra_h = clamp(cra_h, min_h, max_h);
if (cra_w > cra_h) {
   cra_w = cra_h;
}
else if (cra_h > cra_w) {
   cra_h = cra_w;
}
...or you could go the other way, that is, setting the smaller dimension to match the larger dimension instead of setting the larger dimension to match the smaller one. Or you could terminate the process algother if a valid size is not chosen.

Code:
if (cra_w == cra_h) {
   if (cra_w == clamp(cra_w, min_w, max_w) && cra_h == clamp(cra_h, min_h, max_h)) {
      //Continue
   }
}
else {
   //Terminate and ask for a re-input
}
 
F

F Tom

Guest
Thank you for answers, but I solved it like this:
Code:
//scr_init
globalvar tableSizes;
tableSizes = scr_array_create(50); // 50x50 max f.e.

var i;
for (i=1;i< array_length_1d(tableSizes)+1;i++) {
    tableSizes[i-1] = sqr(i); // Fill array with squares
}

//where it's used
recipeHolder = split(recipe,",");
recipeLen = array_length_1d(recipeHolder);

if scr_array_find(tableSizes,recipeLen) = "-7"{
    return "#Error, invalid recipe format"; // Square root not whole number
}
scr_array_create() and split() are my own functions and split doesn't work as intended yet but I will fix it soon. -7 is the default "not found" value of scr_array_find() function
 
Top