i want to see your code

Discussion of programming on Linux, including shell scripting, perl, python, c/c++, mono, java. Whatever tickles your fancy.
Post Reply
lambda
Major General
Posts: 3452
Joined: Tue May 27, 2003 7:04 pm
Location: Lahore
Contact:

i want to see your code

Post by lambda »

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"?
sameer666
Naik
Posts: 82
Joined: Tue Nov 06, 2007 5:31 am

Post by sameer666 »

hi

can u explain more, wat u mean by nearest power of 2?
Novice at heart
wacky
Naik
Posts: 94
Joined: Thu Jun 10, 2004 7:42 pm
Location: London, UK

Post by wacky »

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

Post by wacky »

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++;
}
Post Reply