WeixiangYan/CodeTransOcean huggingface dataset:
Task: Create an HTML table



C#: using System;
using System.Text;

namespace prog
{
	class MainClass
	{		
		public static void Main (string[] args)
		{
			StringBuilder s = new StringBuilder();
			Random rnd = new Random();
			
			s.AppendLine("<table>");
			s.AppendLine("<thead align = \"right\">");
			s.Append("<tr><th></th>");
			for(int i=0; i<3; i++)
				s.Append("<td>" + "XYZ"[i] + "</td>");
			s.AppendLine("</tr>");
			s.AppendLine("</thead>");
			s.AppendLine("<tbody align = \"right\">");
			for( int i=0; i<3; i++ )
			{
				s.Append("<tr><td>"+i+"</td>");
				for( int j=0; j<3; j++ )
					s.Append("<td>"+rnd.Next(10000)+"</td>");				
				s.AppendLine("</tr>");
			}
			s.AppendLine("</tbody>");
			s.AppendLine("</table>");
			
			Console.WriteLine( s );
		}
	}
}




PHP: <?php

$cols = array('', 'X', 'Y', 'Z');
$rows = 3;

$html = '<html><body><table><colgroup>';
foreach($cols as $col)
{
	$html .= '<col style="text-align: left;" />';
}
unset($col);
$html .= '</colgroup><thead><tr>';

foreach($cols as $col)
{
	$html .= "<td>{$col}</td>";
}
unset($col);

$html .= '</tr></thead><tbody>';
for($r = 1; $r <= $rows; $r++)
{
	$html .= '<tr>';
	foreach($cols as $key => $col)
	{
		$html .= '<td>' . (($key > 0) ? rand(1, 9999) : $r) . '</td>';
	}
	unset($col);
	$html .= '</tr>';
}
$html .= '</tbody></table></body></html>';

echo $html;
Task: Create an HTML table


C++: #include <fstream>
#include <boost/array.hpp>
#include <string>
#include <cstdlib>
#include <ctime>
#include <sstream>

void makeGap( int gap , std::string & text ) {
   for ( int i = 0 ; i < gap ; i++ ) 
      text.append( " " ) ;
}

int main( ) {
   boost::array<char , 3> chars = { 'X' , 'Y' , 'Z' } ;
   int headgap = 3 ;
   int bodygap = 3 ;
   int tablegap = 6 ;
   int rowgap = 9 ;
   std::string tabletext( "<html>\n" ) ;
   makeGap( headgap , tabletext ) ;
   tabletext += "<head></head>\n" ;
   makeGap( bodygap , tabletext ) ;
   tabletext += "<body>\n" ;
   makeGap( tablegap , tabletext ) ;
   tabletext += "<table>\n" ;
   makeGap( tablegap + 1 , tabletext ) ;
   tabletext += "<thead align=\"right\">\n" ;
   makeGap( tablegap, tabletext ) ;
   tabletext += "<tr><th></th>" ;
   for ( int i = 0 ; i < 3 ; i++ ) {
      tabletext += "<td>" ;
      tabletext += *(chars.begin( ) + i ) ;
      tabletext += "</td>" ;
   }
   tabletext += "</tr>\n" ;
   makeGap( tablegap + 1 , tabletext ) ;
   tabletext += "</thead>" ;
   makeGap( tablegap + 1 , tabletext ) ;
   tabletext += "<tbody align=\"right\">\n" ;
   srand( time( 0 ) ) ;
   for ( int row = 0 ; row < 5 ; row++ ) {
      makeGap( rowgap , tabletext ) ;
      std::ostringstream oss ;
      tabletext += "<tr><td>" ;
      oss << row ;
      tabletext += oss.str( ) ;
      for ( int col = 0 ; col < 3 ; col++ ) {
	 oss.str( "" ) ;
	 int randnumber = rand( ) % 10000 ;
	 oss << randnumber ;
	 tabletext += "<td>" ;
	 tabletext.append( oss.str( ) ) ;
	 tabletext += "</td>" ;
      }
      tabletext += "</tr>\n" ;
   }
   makeGap( tablegap + 1 , tabletext ) ;
   tabletext += "</tbody>\n" ;
   makeGap( tablegap , tabletext ) ;
   tabletext += "</table>\n" ;
   makeGap( bodygap , tabletext ) ;
   tabletext += "</body>\n" ;
   tabletext += "</html>\n" ;
   std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ;
   htmltable << tabletext ;
   htmltable.close( ) ;
   return 0 ;
}





PHP: <?php

$cols = array('', 'X', 'Y', 'Z');
$rows = 3;

$html = '<html><body><table><colgroup>';
foreach($cols as $col)
{
	$html .= '<col style="text-align: left;" />';
}
unset($col);
$html .= '</colgroup><thead><tr>';

foreach($cols as $col)
{
	$html .= "<td>{$col}</td>";
}
unset($col);

$html .= '</tr></thead><tbody>';
for($r = 1; $r <= $rows; $r++)
{
	$html .= '<tr>';
	foreach($cols as $key => $col)
	{
		$html .= '<td>' . (($key > 0) ? rand(1, 9999) : $r) . '</td>';
	}
	unset($col);
	$html .= '</tr>';
}
$html .= '</tbody></table></body></html>';

echo $html;
Task: Create an HTML table




Go: package main

import (
    "fmt"
    "html/template"
    "os"
)

type row struct {
    X, Y, Z int
}

var tmpl = `<table>
    <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
{{range $ix, $row := .}}    <tr><td>{{$ix}}</td>
        <td>{{$row.X}}</td>
        <td>{{$row.Y}}</td>
        <td>{{$row.Z}}</td></tr>
{{end}}</table>
`

func main() {
    
    ct := template.Must(template.New("").Parse(tmpl))

    
    data := make([]row, 4)
    for r := range data {
        data[r] = row{r*3, r*3+1, r*3+2}
    }

    
    if err := ct.Execute(os.Stdout, data); err != nil {
        fmt.Println(err)
    }
}



PHP: <?php

$cols = array('', 'X', 'Y', 'Z');
$rows = 3;

$html = '<html><body><table><colgroup>';
foreach($cols as $col)
{
	$html .= '<col style="text-align: left;" />';
}
unset($col);
$html .= '</colgroup><thead><tr>';

foreach($cols as $col)
{
	$html .= "<td>{$col}</td>";
}
unset($col);

$html .= '</tr></thead><tbody>';
for($r = 1; $r <= $rows; $r++)
{
	$html .= '<tr>';
	foreach($cols as $key => $col)
	{
		$html .= '<td>' . (($key > 0) ? rand(1, 9999) : $r) . '</td>';
	}
	unset($col);
	$html .= '</tr>';
}
$html .= '</tbody></table></body></html>';

echo $html;
Task: Create an HTML table





Java: public class HTML {

	public static String array2HTML(Object[][] array){
		StringBuilder html = new StringBuilder(
				"<table>");
		for(Object elem:array[0]){
			html.append("<th>" + elem.toString() + "</th>");
		}
		for(int i = 1; i < array.length; i++){
			Object[] row = array[i];
			html.append("<tr>");
			for(Object elem:row){
				html.append("<td>" + elem.toString() + "</td>");
			}
			html.append("</tr>");
		}
		html.append("</table>");
		return html.toString();
	}
	
	public static void main(String[] args){
		Object[][] ints = {{"","X","Y","Z"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}};
		System.out.println(array2HTML(ints));
	}
}


PHP: <?php

$cols = array('', 'X', 'Y', 'Z');
$rows = 3;

$html = '<html><body><table><colgroup>';
foreach($cols as $col)
{
	$html .= '<col style="text-align: left;" />';
}
unset($col);
$html .= '</colgroup><thead><tr>';

foreach($cols as $col)
{
	$html .= "<td>{$col}</td>";
}
unset($col);

$html .= '</tr></thead><tbody>';
for($r = 1; $r <= $rows; $r++)
{
	$html .= '<tr>';
	foreach($cols as $key => $col)
	{
		$html .= '<td>' . (($key > 0) ? rand(1, 9999) : $r) . '</td>';
	}
	unset($col);
	$html .= '</tr>';
}
$html .= '</tbody></table></body></html>';

echo $html;
Task: Create an HTML table






PHP: <?php

$cols = array('', 'X', 'Y', 'Z');
$rows = 3;

$html = '<html><body><table><colgroup>';
foreach($cols as $col)
{
	$html .= '<col style="text-align: left;" />';
}
unset($col);
$html .= '</colgroup><thead><tr>';

foreach($cols as $col)
{
	$html .= "<td>{$col}</td>";
}
unset($col);

$html .= '</tr></thead><tbody>';
for($r = 1; $r <= $rows; $r++)
{
	$html .= '<tr>';
	foreach($cols as $key => $col)
	{
		$html .= '<td>' . (($key > 0) ? rand(1, 9999) : $r) . '</td>';
	}
	unset($col);
	$html .= '</tr>';
}
$html .= '</tbody></table></body></html>';

echo $html;


Python: import random

def rand9999():
    return random.randint(1000, 9999)

def tag(attr='', **kwargs):
    for tag, txt in kwargs.items():
        return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())

if __name__ == '__main__':
    header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n'
    rows = '\n'.join(tag(tr=tag(' style="font-weight: bold;"', td=i)
                                    + ''.join(tag(td=rand9999())
                                              for j in range(3)))
                     for i in range(1, 6))
    table = tag(table='\n' + header + rows + '\n')
    print(table)
Task: Create an HTML table






PHP: <?php

$cols = array('', 'X', 'Y', 'Z');
$rows = 3;

$html = '<html><body><table><colgroup>';
foreach($cols as $col)
{
	$html .= '<col style="text-align: left;" />';
}
unset($col);
$html .= '</colgroup><thead><tr>';

foreach($cols as $col)
{
	$html .= "<td>{$col}</td>";
}
unset($col);

$html .= '</tr></thead><tbody>';
for($r = 1; $r <= $rows; $r++)
{
	$html .= '<tr>';
	foreach($cols as $key => $col)
	{
		$html .= '<td>' . (($key > 0) ? rand(1, 9999) : $r) . '</td>';
	}
	unset($col);
	$html .= '</tr>';
}
$html .= '</tbody></table></body></html>';

echo $html;



VB: Set objFSO = CreateObject("Scripting.FileSystemObject")


Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
	"\in.csv",1)
	

Set objOutHTML = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
	"\out.html",2,True)


objOutHTML.Write "<html><head></head><body>" & vbCrLf


objOutHTML.Write "<table border=1 cellpadding=10 cellspacing=0>" & vbCrLf


objOutHTML.Write "<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>" & vbCrLf


n = 1
Do Until objInFile.AtEndOfStream
	line = objInFile.ReadLine
	If Len(line) > 0 Then
		token = Split(line,",")
		objOutHTML.Write "<tr align=""right""><td>" & n & "</td>"
		For i = 0 To UBound(token)
			objOutHTML.Write "<td>" & token(i) & "</td>"
		Next
		objOutHTML.Write "</tr>" & vbCrLf
	End If
	n = n + 1
Loop


objOutHTML.Write "</table></body></html>"

objInFile.Close
objOutHTML.Close
Set objFSO = Nothing
Task: Rosetta Code_Rank languages by popularity

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char * lang_url = "http:
		"list=categorymembers&cmtitle=Category:Programming_Languages&"
		"cmlimit=500&format=json";
const char * cat_url = "http:

#define BLOCK 1024
char *get_page(const char *url)
{
	char cmd[1024];
	char *ptr, *buf;
	int bytes_read = 1, len = 0;
	sprintf(cmd, "wget -q \"%s\" -O -", url);
	FILE *fp = popen(cmd, "r");
	if (!fp) return 0;
	for (ptr = buf = 0; bytes_read > 0; ) {
		buf = realloc(buf, 1 + (len += BLOCK));
		if (!ptr) ptr = buf;
		bytes_read = fread(ptr, 1, BLOCK, fp);
		if (bytes_read <= 0) break;
		ptr += bytes_read;
	}
	*++ptr = '\0';
	return buf;
}

char ** get_langs(char *buf, int *l)
{
	char **arr = 0;
	for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
		for (	(*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
			*buf != '"' || (*buf++ = 0);
			buf++);

	return arr;
}

typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
	char str[1024], *found;
	cnt_t *list = 0;
	int i, llen = 0;
	for (i = 0; i < len; i++) {
		sprintf(str, "/wiki/Category:%s", langs[i]);
		if (!(found = strstr(buf, str))) continue;
		buf = found + strlen(str);

		if (!(found = strstr(buf, "</a> ("))) continue;
		list = realloc(list, sizeof(cnt_t) * ++llen);
		list[llen - 1].name = langs[i];
		list[llen - 1].count = strtol(found + 6, 0, 10);
	}
	*ret_len = llen;
	return list;
}

int _scmp(const void *a, const void *b)
{
	int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
	return x < y ? -1 : x > y;
}

int main()
{
	int len, clen;
	char ** langs = get_langs(get_page(lang_url), &len);
	cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
	qsort(cats, clen, sizeof(cnt_t), _scmp);
	while (--clen >= 0)
		printf("%4d %s\n", cats[clen].count, cats[clen].name);

	return 0;
}



C#: using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string get1 = new WebClient().DownloadString("http:
        string get2 = new WebClient().DownloadString("http:

        ArrayList langs = new ArrayList();
        Dictionary<string, int> qtdmbr = new Dictionary<string, int>();

        MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
        MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);

        foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);

        foreach (Match match in match2)
        {
            if (langs.Contains(match.Groups[1].Value))
            {
                qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
            }
        }

        string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();

        int count = 1;

        foreach (string i in test)
        {
            Console.WriteLine("{0,3}. {1}", count, i);
            count++;
        }
    }
}
Task: Rosetta Code_Rank languages by popularity



C#: using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string get1 = new WebClient().DownloadString("http:
        string get2 = new WebClient().DownloadString("http:

        ArrayList langs = new ArrayList();
        Dictionary<string, int> qtdmbr = new Dictionary<string, int>();

        MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
        MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?</a>[^(]*\\((\\d+) members\\)").Matches(get2);

        foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);

        foreach (Match match in match2)
        {
            if (langs.Contains(match.Groups[1].Value))
            {
                qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
            }
        }

        string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();

        int count = 1;

        foreach (string i in test)
        {
            Console.WriteLine("{0,3}. {1}", count, i);
            count++;
        }
    }
}





Python: import requests
import re

response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3] 

response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)           
members  = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response) 

for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]): 
    if language in languages:
        print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
Task: Rosetta Code_Rank languages by popularity




Go: package main

import (
	"encoding/xml"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"regexp"
	"sort"
	"strconv"
	"strings"
)

var baseQuery = "http:
	"&format=xml&list=categorymembers&cmlimit=500"

func req(u string, foundCm func(string)) string {
	resp, err := http.Get(u)
	if err != nil {
		log.Fatal(err) 
	}
	defer resp.Body.Close()
	for p := xml.NewDecoder(resp.Body); ; {
		t, err := p.RawToken()
		switch s, ok := t.(xml.StartElement); {
		case err == io.EOF:
			return ""
		case err != nil:
			log.Fatal(err)
		case !ok:
			continue
		case s.Name.Local == "cm":
			for _, a := range s.Attr {
				if a.Name.Local == "title" {
					foundCm(a.Value)
				}
			}
		case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
			s.Attr[0].Name.Local == "cmcontinue":
			return url.QueryEscape(s.Attr[0].Value)
		}
	}
	return ""
}


type pop struct {
	string
	int
}
type popList []pop

func (pl popList) Len() int      { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
	switch d := pl[i].int - pl[j].int; {
	case d > 0:
		return true
	case d < 0:
		return false
	}
	return pl[i].string < pl[j].string
}

func main() {
	
	langMap := make(map[string]bool)
	storeLang := func(cm string) {
		if strings.HasPrefix(cm, "Category:") {
			cm = cm[9:]
		}
		langMap[cm] = true
	}
	languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
	continueAt := req(languageQuery, storeLang)
	for continueAt != "" {
		continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
	}
	
	s := make(popList, 0, len(langMap))

	
	resp, err := http.Get("http:
		"?title=Special:Categories&limit=5000")
	if err != nil {
		log.Fatal(err)
	}
	page, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	
	rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member")
	for _, sm := range rx.FindAllSubmatch(page, -1) {
		ls := string(sm[1])
		if langMap[ls] {
			if n, err := strconv.Atoi(string(sm[2])); err == nil {
				s = append(s, pop{ls, n})
			}
		}
	}

	
	sort.Sort(s)
	lastCnt, lastIdx := -1, 1
	for i, lang := range s {
		if lang.int != lastCnt {
			lastCnt = lang.int
			lastIdx = i + 1
		}
		fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
	}
}




Python: import requests
import re

response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3] 

response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)           
members  = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response) 

for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]): 
    if language in languages:
        print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
Task: Rosetta Code_Rank languages by popularity

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char * lang_url = "http:
		"list=categorymembers&cmtitle=Category:Programming_Languages&"
		"cmlimit=500&format=json";
const char * cat_url = "http:

#define BLOCK 1024
char *get_page(const char *url)
{
	char cmd[1024];
	char *ptr, *buf;
	int bytes_read = 1, len = 0;
	sprintf(cmd, "wget -q \"%s\" -O -", url);
	FILE *fp = popen(cmd, "r");
	if (!fp) return 0;
	for (ptr = buf = 0; bytes_read > 0; ) {
		buf = realloc(buf, 1 + (len += BLOCK));
		if (!ptr) ptr = buf;
		bytes_read = fread(ptr, 1, BLOCK, fp);
		if (bytes_read <= 0) break;
		ptr += bytes_read;
	}
	*++ptr = '\0';
	return buf;
}

char ** get_langs(char *buf, int *l)
{
	char **arr = 0;
	for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
		for (	(*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
			*buf != '"' || (*buf++ = 0);
			buf++);

	return arr;
}

typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
	char str[1024], *found;
	cnt_t *list = 0;
	int i, llen = 0;
	for (i = 0; i < len; i++) {
		sprintf(str, "/wiki/Category:%s", langs[i]);
		if (!(found = strstr(buf, str))) continue;
		buf = found + strlen(str);

		if (!(found = strstr(buf, "</a> ("))) continue;
		list = realloc(list, sizeof(cnt_t) * ++llen);
		list[llen - 1].name = langs[i];
		list[llen - 1].count = strtol(found + 6, 0, 10);
	}
	*ret_len = llen;
	return list;
}

int _scmp(const void *a, const void *b)
{
	int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
	return x < y ? -1 : x > y;
}

int main()
{
	int len, clen;
	char ** langs = get_langs(get_page(lang_url), &len);
	cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
	qsort(cats, clen, sizeof(cnt_t), _scmp);
	while (--clen >= 0)
		printf("%4d %s\n", cats[clen].count, cats[clen].name);

	return 0;
}







Python: import requests
import re

response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3] 

response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)           
members  = re.findall('<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>',response) 

for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]): 
    if language in languages:
        print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))
Task: Exponentiation operator

C: #include <stdio.h>
#include <assert.h>

int ipow(int base, int exp)
{
   int pow = base;
   int v = 1;
   if (exp < 0) {
      assert (base != 0);  
      return (base*base != 1)? 0: (exp&1)? base : 1;
   }
       
   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
    }
   return v;
}

double dpow(double base, int exp)
{
   double v=1.0;
   double pow = (exp <0)? 1.0/base : base;
   if (exp < 0) exp = - exp;

   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
   }
   return v;
}

int main()
{
    printf("2^6 = %d\n", ipow(2,6));
    printf("2^-6 = %d\n", ipow(2,-6));
    printf("2.71^6 = %lf\n", dpow(2.71,6));
    printf("2.71^-6 = %lf\n", dpow(2.71,-6));
}



C#: static void Main(string[] args)
{
	Console.WriteLine("5^5 = " + Expon(5, 5));
	Console.WriteLine("5.5^5 = " + Expon(5.5, 5));
	Console.ReadLine();
}

static double Expon(int Val, int Pow) 
{
	return Math.Pow(Val, Pow);
}
static double Expon(double Val, int Pow)
{
	return Math.Pow(Val, Pow);
}
Task: Exponentiation operator

C: #include <stdio.h>
#include <assert.h>

int ipow(int base, int exp)
{
   int pow = base;
   int v = 1;
   if (exp < 0) {
      assert (base != 0);  
      return (base*base != 1)? 0: (exp&1)? base : 1;
   }
       
   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
    }
   return v;
}

double dpow(double base, int exp)
{
   double v=1.0;
   double pow = (exp <0)? 1.0/base : base;
   if (exp < 0) exp = - exp;

   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
   }
   return v;
}

int main()
{
    printf("2^6 = %d\n", ipow(2,6));
    printf("2^-6 = %d\n", ipow(2,-6));
    printf("2.71^6 = %lf\n", dpow(2.71,6));
    printf("2.71^-6 = %lf\n", dpow(2.71,-6));
}


C++: template<typename Number>
 Number power(Number base, int exponent)
{
  int zerodir;
  Number factor;
  if (exponent < 0)
  {
    zerodir = 1;
    factor = Number(1)/base;
  }
  else
  {
    zerodir = -1;
    factor = base;
  }

  Number result(1);
  while (exponent != 0)
  {
    if (exponent % 2 != 0)
    {
      result *= factor;
      exponent += zerodir;
    }
    else
    {
      factor *= factor;
      exponent /= 2;
    }
  }
  return result;
}
Task: Exponentiation operator

C: #include <stdio.h>
#include <assert.h>

int ipow(int base, int exp)
{
   int pow = base;
   int v = 1;
   if (exp < 0) {
      assert (base != 0);  
      return (base*base != 1)? 0: (exp&1)? base : 1;
   }
       
   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
    }
   return v;
}

double dpow(double base, int exp)
{
   double v=1.0;
   double pow = (exp <0)? 1.0/base : base;
   if (exp < 0) exp = - exp;

   while(exp > 0 )
   {
      if (exp & 1) v *= pow;
      pow *= pow;
      exp >>= 1;
   }
   return v;
}

int main()
{
    printf("2^6 = %d\n", ipow(2,6));
    printf("2^-6 = %d\n", ipow(2,-6));
    printf("2.71^6 = %lf\n", dpow(2.71,6));
    printf("2.71^-6 = %lf\n", dpow(2.71,-6));
}




Go: package main

import (
    "errors"
    "fmt"
)

func expI(b, p int) (int, error) {
    if p < 0 {
        return 0, errors.New("negative power not allowed")
    }
    r := 1
    for i := 1; i <= p; i++ {
        r *= b
    }
    return r, nil
}

func expF(b float32, p int) float32 {
    var neg bool
    if p < 0 {
        neg = true
        p = -p
    }
    r := float32(1)
    for pow := b; p > 0; pow *= pow {
        if p&1 == 1 {
            r *= pow
        }
        p >>= 1
    }
    if neg {
        r = 1 / r
    }
    return r
}

func main() {
    ti := func(b, p int) {
        fmt.Printf("%d^%d: ", b, p)
        e, err := expI(b, p)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Println(e)
        }
    }

    fmt.Println("expI tests")
    ti(2, 10)
    ti(2, -10)
    ti(-2, 10)
    ti(-2, 11)
    ti(11, 0)

    fmt.Println("overflow undetected")
    ti(10, 10)

    tf := func(b float32, p int) {
        fmt.Printf("%g^%d: %g\n", b, p, expF(b, p))
    }

    fmt.Println("\nexpF tests:")
    tf(2, 10)
    tf(2, -10)
    tf(-2, 10)
    tf(-2, 11)
    tf(11, 0)

    fmt.Println("disallowed in expI, allowed here")
    tf(0, -1)

    fmt.Println("other interesting cases for 32 bit float type")
    tf(10, 39)
    tf(10, -39)
    tf(-10, 39)
}