0

How can get a perfect square of list of numbers except for integers that is a square of a previous integer in the list.

for input of 30 following are the results:

1
2
3
square
5
6
7
8
square
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
square
26
27
28
29
30

I can get the result only for perfect square but the issues is, i am also getting 16 as square. which it's not consider as square since 4 is already a square. Thanks.

4

4 回答 4

2

If you want to check whether a number is "perfect square":

  1. Check if sqrt() is a integer.
  2. If yes, check if that is a prime number

If you want to generate perfect squares,

  1. Generate prime numbers
  2. Compute their squares
于 2013-09-23T05:39:02.547 回答
1

Add perfect square to a look up array and check if already it is a perfect square then ignore it.

Use:

<?php

$isAlreadySquare = array();
for($i=1; $i<=30; $i++) {

    $isSquare = false;
    for($j=1; $j<$i; $j++) {
        $s = $j*$j;
        if($s==$i && !in_array($j,$isAlreadySquare)) {
            $isAlreadySquare[] = $i;
            $isSquare = true;
        }

    }

    if($isSquare) {
        echo "square<br>";
    } else {
        echo $i."<br>";
    }
}

?>
于 2013-09-23T05:25:24.610 回答
1

Just an another solution:

$sq = $u = array();
for($i = 1; $i <= 30; $i++) {
    $t = sqrt($i);
    if ((int) $t == $t) {
        $sq[] = $i;
    }
}

foreach ($sq as $v) {
    if (!in_array(sqrt($v), $sq)) {
        $u[] = $v;
    }
}

print_r($u);

Array
(
    [0] => 4
    [1] => 9
    [2] => 25
)
于 2013-09-23T06:01:42.510 回答
0

One of the solution that come to my mind is to keep the lookup array or dictionary kind of data structure and when ever you get the perfect square keep the square value and put the condition as this , As you are going in order you can remove the element from the lookup table used below condition is met, because in sorted numbers you are not going to get it again.

                  Is Number Perfect square && Not available in lookup table 
于 2013-09-23T05:26:16.060 回答