Sponsored Content
Operating Systems OS X (Apple) A Fun Perfect Square Checker Using Integer Arithmetic Only... ;o) Post 302952764 by Corona688 on Friday 21st of August 2015 12:07:04 PM
Old 08-21-2015
Binary search was a good idea. Needed to watch a few edge cases.

Code:
#!/bin/bash

VAL=${1-100}
MN=1
MX="$((VAL))"
[ "$MX" -ge 3037000499 ] && MX=3037000499 # Square root of highest possible perfect square

function die() {
        local CODE=$1 ; shift
        echo "$@" >&2 ; exit $CODE
}

[ "$VAL" -lt 0 ] && die 1 "Negative numbers not allowed"

while (((MX-MN) > 1 ))
do
        if (( (((MN+MX)/2) * ((MN+MX)/2)) > VAL )) ; then
                MX=$(( (MN+MX) / 2 ))
        elif (( (((MN+MX)/2) * ((MN+MX)/2)) < VAL )) ; then
                MN=$(( (MN+MX) / 2 ))
        else
                break;
        fi
done

(( (((MN+MX)/2) * ((MN+MX)/2)) == VAL )) &&
        die 0 "Square root of $VAL is $(( (MN+MX)/2 ))"

die 1 "$VAL is not a perfect square"

Code:
$ time ./psquare.sh $(( 300000 * 300000 ))
MN=299968, MX=300032
Square root of 90000000000 is 300000

real    0m0.004s
user    0m0.003s
sys     0m0.000s
$


Last edited by Corona688; 08-21-2015 at 01:29 PM..
 

8 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

extraction of perfect text from file.

Hi All, I have a file of the following format. <?xml version='1.0' encoding='utf-8'?> <tomcat-users> <role rolename="tomcat"/> <role rolename="role1"/> <role rolename="manager"/> <role rolename="admin"/> <user username="tomcat" password="tomcat" roles="tomcat"/> <user... (5 Replies)
Discussion started by: nua7
5 Replies

2. UNIX for Dummies Questions & Answers

A perfect number shell program

Here's my work of testing whether a number input is perfect or not.. echo Enter a number read no i=1 ans=0 while do if then ans='expr $ans + $i' fi i='expr $i + 1' done if then echo $no is perfect else echo $no is NOT perfect fi (12 Replies)
Discussion started by: Cyansnow
12 Replies

3. AIX

I want the perfect user-interface

I've got an aix-box somewhere on the network and a PC on my desk. Nothing fancy so far. The PC is made dual-boot: - windowsXP with putty & winSCP or - slackware 13 with xfce4 installed. The aix-box runs DB2 v8.2 and I've installed db2top to monitor the database. db2top is a character... (0 Replies)
Discussion started by: dr_te_z
0 Replies

4. Shell Programming and Scripting

Delete text between square brackets and also delete those square brackets using sed or awk

Hi All, I have a text file which looks like this: computer programming systems engineering I want to get rid of these square brackets and also the text that is inside these brackets. So that my final text file looks like this: computer programming systems engineering I am using... (3 Replies)
Discussion started by: shoaibjameel123
3 Replies

5. Shell Programming and Scripting

how to compare string integer with an integer?

hi, how to I do this? i="4.000" if ; then echo "smaller" fi how do I convert the "4.000" to 4? Thanks! (4 Replies)
Discussion started by: h0ujun
4 Replies

6. UNIX for Dummies Questions & Answers

Can you perfect my sed ?

I want to print only the lines that meet the criteria : "worde:" and "wordo;" I got this far: sed -n '/\(*\)\1e:\1o;/p;' But it doesn't quite work. Can someone please perfect it and tell me exactly how its a fixed version/what was wrong with mine? Thanks heaps, (1 Reply)
Discussion started by: maximus73
1 Replies

7. Shell Programming and Scripting

egrep line with perfect mach

Hi Input File A L006 AL01 0 (OCK) L006 A006 0 (OCK) L011 AR11 1 (NLOCK) Input File B L006 AL01 0 (OCK) L006 A006 0 (OCK) Need Egrep Command for perfect Match Thanks (4 Replies)
Discussion started by: asavaliya
4 Replies

8. Shell Programming and Scripting

Not able to find the perfect code...Geting confused in between

I have to find last delimiter in each line of a file and store the value after the last '/' in a variable in ksh script...Pls Pls help me:(The file is as shown below: /opt/apps/cobqa/apps/abadv/bind/advc0007.bnd /opt/apps/cobqa/apps/abbrio/bind/naac6115.bnd... (5 Replies)
Discussion started by: bhavanabahety
5 Replies
EXAMPLES-WITH-PDO_4D(3) 						 1						   EXAMPLES-WITH-PDO_4D(3)

Examples with PDO_4D - Examples PDO_4D

	This basic example show how to connect, execute a query, read data and disconnect from a 4D SQL server.

       Example #1

	      Basic example with PDO_4D

	      <?php
	      $dsn = '4D:host=localhost;charset=UTF-8';
	      $user = 'test';
	      $pass = 'test';

	      // Connection to the 4D SQL server
	      $db = new PDO($dsn, $user, $pass);

	      try {
		  $db->exec('CREATE TABLE test(id varCHAR(1) NOT NULL, val VARCHAR(10))');
	      } catch (PDOException $e) {
		  die("Erreur 4D : " . $e->getMessage());
	      }

	      $db->exec("INSERT INTO test VALUES('A', 'B')");
	      $db->exec("INSERT INTO test VALUES('C', 'D')");
	      $db->exec("INSERT INTO test VALUES('E', 'F')");

	      $stmt = $db->prepare('SELECT id, val from test');

	      $stmt->execute();
	      print_r($stmt->fetchAll());

	      unset($stmt);
	      unset($db);
	      ?>

	      The above example will output:

	      Array
	      (
		  [0] => Array
		      (
			  [ID] => A
			  [0] => A
			  [VAL] => B
			  [1] => B
		      )

		  [1] => Array
		      (
			  [ID] => C
			  [0] => C
			  [VAL] => D
			  [1] => D
		      )

		  [2] => Array
		      (
			  [ID] => E
			  [0] => E
			  [VAL] => F
			  [1] => F
		      )

	      )

	This example shows how to execute a query in 4D language, and how to read the result through PDO_4D.

       Example #2

	      Accessing 4D language from pdo_4d

	       Set  up a 4D method, called method. Make sure in the method properties that the option Available via SQL is checked. The 4D code is
	      the following.

	      C_TEXTE($0)
	      $0:=Version application(*);

	       The PHP code to use the above 4D method is :

	      <?php
	      $dsn = '4D:host=localhost;charset=UTF-8';
	      $user = 'test';
	      $pass = 'test';

	      // Connection to the 4D server
	      $db = new PDO($dsn, $user, $pass);

	      $stmt = $db->prepare('SELECT {FN method() AS VARCHAR } FROM _USER_SCHEMAS LIMIT 1');

	      $stmt->execute();
	      print_r($stmt->fetchAll());

	      unset($stmt);
	      unset($db);
	      ?>

	      The above example will output:

	      (
		  [0] => Array
		      (
			  [<expression>] => F0011140
			  [0] => F0011140
		      )

	      )

       Example #3

	      Escaping 4D table names

	       This examples illustrates how to escape characters in a 4D SQL query.

	      <?php
	      $dsn = '4D:host=localhost;charset=UTF-8';
	      $user = 'test';
	      $pass = 'test';

	      // Connection to 4D server 4D
	      $db = new PDO($dsn, $user, $pass);

	      $objects = array('[',']','[]','][','[[',']]','[[[',']]]','TBL ]]32[23');

	      foreach($objects as $id => $object) {
		  $object = str_replace(']',']]', $object);
		  print "$object
";

		  $db->exec('CREATE TABLE IF NOT EXISTS ['.$object.'](['.$object.'] FLOAT)');

		  $req = "INSERT INTO [$object] ([$object]) VALUES ($id);";
		  $db->query($req);

		  $q = $db->prepare("SELECT [$object] FROM [$object]");
		  $q->execute();
		  $x[] = $q->fetch(PDO::FETCH_NUM);

		  $db->exec('DROP TABLE ['.$object.'];');
	      }

	      ?>

	      The above example will output:

	      [
	      ]]
	      []]
	      ]][
	      [[
	      ]]]]
	      [[[
	      ]]]]]]
	      TBL ]]]]32[23

PHP Documentation Group 												   EXAMPLES-WITH-PDO_4D(3)
All times are GMT -4. The time now is 01:56 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy