i want to see your code

Discussion of programming on Linux, including shell scripting, perl, python, c/c++, mono, java. Whatever tickles your fancy.

i want to see your code

Postby lambda » Fri Nov 02, 2007 12:10 am

you are given a number. it's a simple integer, like 6 or 144 (positive). you're told to round it up to the nearest power of 2. for 6 that's 8, for 144, it's 256.

post your solution.
Watch out for the Manners Taliban!
Isn't it amazing how so many people can type "linuxpakistan.net" into their browsers but not "google.com"?
lambda
Major General
 
Posts: 3452
Joined: Tue May 27, 2003 7:04 pm
Website: http://www.hungry.com/~fn/
Location: Lahore

Postby sameer666 » Thu Nov 08, 2007 3:32 am

hi

can u explain more, wat u mean by nearest power of 2?
Novice at heart
sameer666
Naik
 
Posts: 82
Joined: Tue Nov 06, 2007 5:31 am

Postby wacky » Thu Nov 08, 2007 1:46 pm

Quite straightfoward. This is a bash shell example :


Code: Select all

#! /bin/bash

echo "Enter your number (positive integer): "
read number

i=1

while true
do
let "z=2**$i"
if [ $z -gt $number ]; then
        echo "$z is the number - 2 to the power of $i"
        exit
fi
let "i+=1"
done
wacky
Naik
 
Posts: 94
Joined: Thu Jun 10, 2004 7:42 pm
Location: London, UK

Postby wacky » Thu Nov 08, 2007 3:10 pm

Same thing in perl :

Code: Select all

#! /usr/bin/perl

print "Enter your number (positive integer): ";
chomp ($number = <>);

$i=1;

while (1) {
        $z = 2 ** $i;
        if ( $z > $number ) {
                print "The number is $z - 2 to the power of $i\n";
                last;
        }
        $i++;
}
wacky
Naik
 
Posts: 94
Joined: Thu Jun 10, 2004 7:42 pm
Location: London, UK


Return to “%s” Programming

Who is online

Users browsing this forum: No registered users and 2 guests

cron