WeixiangYan/CodeTransOcean huggingface dataset:
Task: Power set








VB: Option Base 1
Private Function power_set(ByRef st As Collection) As Collection
    Dim subset As Collection, pwset As New Collection
    For i = 0 To 2 ^ st.Count - 1
        Set subset = New Collection
        For j = 1 To st.Count
            If i And 2 ^ (j - 1) Then subset.Add st(j)
        Next j
        pwset.Add subset
    Next i
    Set power_set = pwset
End Function
Private Function print_set(ByRef st As Collection) As String
    
    Dim s() As String, t() As String
    ReDim s(st.Count)
    
    For i = 1 To st.Count
        If st(i).Count > 0 Then
            ReDim t(st(i).Count)
            For j = 1 To st(i).Count
                Select Case TypeName(st(i)(j))
                    Case "Integer": t(j) = CStr(st(i)(j))
                    Case "Collection": t(j) = "{}" 
                End Select
            Next j
            s(i) = "{" & Join(t, ", ") & "}"
        Else
            s(i) = "{}"
        End If
    Next i
    print_set = "{" & Join(s, ", ") & "}"
End Function
Public Sub rc()
    Dim rcset As New Collection, result As Collection
    For i = 1 To 4
        rcset.Add i
    Next i
    Debug.Print print_set(power_set(rcset))
    Set rcset = New Collection
    Debug.Print print_set(power_set(rcset))
    Dim emptyset As New Collection
    rcset.Add emptyset
    Debug.Print print_set(power_set(rcset))
    Debug.Print
End Sub




Ada: with Ada.Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Command_Line;
 
procedure powerset is
begin
	for set in 0..2**Argument_Count-1 loop
		Put ("{");			
		declare
			k : natural := set;
			first : boolean := true;
		begin
			for i in 1..Argument_Count loop
				if k mod 2 = 1 then
					Put ((if first then "" else ",") & Argument (i));
					first := false;
			  	end if;
				k := k / 2; 
			end loop;
		end;
		Put_Line("}");
	end loop;
end powerset;
Task: Power set

C: #include <stdio.h>

struct node {
	char *s;
	struct node* prev;
};

void powerset(char **v, int n, struct node *up)
{
	struct node me;

	if (!n) {
		putchar('[');
		while (up) {
			printf(" %s", up->s);
			up = up->prev;
		}
		puts(" ]");
	} else {
		me.s = *v;
		me.prev = up;
		powerset(v + 1, n - 1, up);
		powerset(v + 1, n - 1, &me);
	}
}

int main(int argc, char **argv)
{
	powerset(argv + 1, argc - 1, 0);
	return 0;
}
Task: Power set



C#: public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
    return from m in Enumerable.Range(0, 1 << list.Count)
                  select
                      from i in Enumerable.Range(0, list.Count)
                      where (m & (1 << i)) != 0
                      select list[i];
}

public void PowerSetofColors()
{
    var colors = new List<KnownColor> { KnownColor.Red, KnownColor.Green, 
        KnownColor.Blue, KnownColor.Yellow };
    
    var result = GetPowerSet(colors);
    
    Console.Write( string.Join( Environment.NewLine, 
        result.Select(subset => 
            string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));
}
Task: Power set


C++: #include <iostream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
typedef std::set<int> set_type;
typedef std::set<set_type> powerset_type;

powerset_type powerset(set_type const& set)
{
  typedef set_type::const_iterator set_iter;
  typedef std::vector<set_iter> vec;
  typedef vec::iterator vec_iter;

  struct local
  {
    static int dereference(set_iter v) { return *v; }
  };

  powerset_type result;

  vec elements;
  do
  {
    set_type tmp;
    std::transform(elements.begin(), elements.end(),
                   std::inserter(tmp, tmp.end()),
                   local::dereference);
    result.insert(tmp);
    if (!elements.empty() && ++elements.back() == set.end())
    {
      elements.pop_back();
    }
    else
    {
      set_iter iter;
      if (elements.empty())
      {
        iter = set.begin();
      }
      else
      {
        iter = elements.back();
        ++iter;
      }
      for (; iter != set.end(); ++iter)
      {
        elements.push_back(iter);
      }
    }
  } while (!elements.empty());

  return result;
}

int main()
{
  int values[4] = { 2, 3, 5, 7 };
  set_type test_set(values, values+4);

  powerset_type test_powerset = powerset(test_set);

  for (powerset_type::iterator iter = test_powerset.begin();
       iter != test_powerset.end();
       ++iter)
  {
    std::cout << "{ ";
    char const* prefix = "";
    for (set_type::iterator iter2 = iter->begin();
         iter2 != iter->end();
         ++iter2)
    {
      std::cout << prefix << *iter2;
      prefix = ", ";
    }
    std::cout << " }\n";
  }
}
Task: Power set





Java: public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps)
    {
        if(n<0)
        {
            return null;
        }
        if(n==0)
        {
            if(ps==null)
                ps=new ArrayList<String>();
            ps.add(" ");
            return ps;
        }
        ps=getpowerset(a, n-1, ps);
        ArrayList<String> tmp=new ArrayList<String>();
        for(String s:ps)
        {
            if(s.equals(" "))
                tmp.add(""+a[n-1]);
            else
                tmp.add(s+a[n-1]);
        }
        ps.addAll(tmp);
        return ps;
    }
Task: Power set







Python: def list_powerset(lst):
    
    result = [[]]
    for x in lst:
        
        
        
        
        
        
        result.extend([subset + [x] for subset in result])
    return result


def list_powerset2(lst):
    return reduce(lambda result, x: result + [subset + [x] for subset in result],
                  lst, [[]])

def powerset(s):
    return frozenset(map(frozenset, list_powerset(list(s))))
Task: Power set








VB: Option Base 1
Private Function power_set(ByRef st As Collection) As Collection
    Dim subset As Collection, pwset As New Collection
    For i = 0 To 2 ^ st.Count - 1
        Set subset = New Collection
        For j = 1 To st.Count
            If i And 2 ^ (j - 1) Then subset.Add st(j)
        Next j
        pwset.Add subset
    Next i
    Set power_set = pwset
End Function
Private Function print_set(ByRef st As Collection) As String
    
    Dim s() As String, t() As String
    ReDim s(st.Count)
    
    For i = 1 To st.Count
        If st(i).Count > 0 Then
            ReDim t(st(i).Count)
            For j = 1 To st(i).Count
                Select Case TypeName(st(i)(j))
                    Case "Integer": t(j) = CStr(st(i)(j))
                    Case "Collection": t(j) = "{}" 
                End Select
            Next j
            s(i) = "{" & Join(t, ", ") & "}"
        Else
            s(i) = "{}"
        End If
    Next i
    print_set = "{" & Join(s, ", ") & "}"
End Function
Public Sub rc()
    Dim rcset As New Collection, result As Collection
    For i = 1 To 4
        rcset.Add i
    Next i
    Debug.Print print_set(power_set(rcset))
    Set rcset = New Collection
    Debug.Print print_set(power_set(rcset))
    Dim emptyset As New Collection
    rcset.Add emptyset
    Debug.Print print_set(power_set(rcset))
    Debug.Print
End Sub
Task: Power set




Go: package main

import (
    "fmt"
    "strconv"
    "strings"
)





type elem interface {
    
    
    
    Eq(elem) bool
    
    
    fmt.Stringer
}


type Int int

func (i Int) Eq(e elem) bool {
    j, ok := e.(Int)
    return ok && i == j
}

func (i Int) String() string {
    return strconv.Itoa(int(i))
}



type set []elem


func (s *set) add(e elem) {
    if !s.has(e) {
        *s = append(*s, e)
    }
}

func (s *set) has(e elem) bool {
    for _, ex := range *s {
        if e.Eq(ex) {
            return true
        }
    }
    return false
}

func (s set) ok() bool {
    for i, e0 := range s {
        for _, e1 := range s[i+1:] {
            if e0.Eq(e1) {
                return false
            }
        }
    }
    return true
}


func (s set) Eq(e elem) bool {
    t, ok := e.(set)
    if !ok {
        return false
    }
    if len(s) != len(t) {
        return false
    }
    for _, se := range s {
        if !t.has(se) {
            return false
        }
    }
    return true
}


func (s set) String() string {
    if len(s) == 0 {
        return "∅"
    }
    var buf strings.Builder
    buf.WriteRune('{')
    for i, e := range s {
        if i > 0 {
            buf.WriteRune(',')
        }
        buf.WriteString(e.String())
    }
    buf.WriteRune('}')
    return buf.String()
}


func (s set) powerSet() set {
    r := set{set{}}
    for _, es := range s {
        var u set
        for _, er := range r {
            er := er.(set)
            u = append(u, append(er[:len(er):len(er)], es))
        }
        r = append(r, u...)
    }
    return r
}

func main() {
    var s set
    for _, i := range []Int{1, 2, 2, 3, 4, 4, 4} {
        s.add(i)
    }
    fmt.Println("      s:", s, "length:", len(s))
    ps := s.powerSet()
    fmt.Println("   𝑷(s):", ps, "length:", len(ps))

    fmt.Println("\n(extra credit)")
    var empty set
    fmt.Println("  empty:", empty, "len:", len(empty))
    ps = empty.powerSet()
    fmt.Println("   𝑷(∅):", ps, "len:", len(ps))
    ps = ps.powerSet()
    fmt.Println("𝑷(𝑷(∅)):", ps, "len:", len(ps))

    fmt.Println("\n(regression test for earlier bug)")
    s = set{Int(1), Int(2), Int(3), Int(4), Int(5)}
    fmt.Println("      s:", s, "length:", len(s), "ok:", s.ok())
    ps = s.powerSet()
    fmt.Println("   𝑷(s):", "length:", len(ps), "ok:", ps.ok())
    for _, e := range ps {
        if !e.(set).ok() {
            panic("invalid set in ps")
        }
    }
}
Task: Power set






PHP: <?php
function get_subset($binary, $arr) {


  $subset = array();
  foreach (range(0, count($arr)-1) as $i) {
    if ($binary[$i]) {
      $subset[] = $arr[count($arr) - $i - 1];
    } 
  }
  return $subset;
}

function print_array($arr) {
  if (count($arr) > 0) {
    echo join(" ", $arr);
  } else {
    echo "(empty)";
  }
  echo '<br>';
}

function print_power_sets($arr) {
  echo "POWER SET of [" . join(", ", $arr) . "]<br>";
  foreach (power_set($arr) as $subset) {
    print_array($subset);
  }
}
  
function power_set($arr) {  
  $binary = array();
  foreach (range(1, count($arr)) as $i) {
    $binary[] = false;
  }
  $n = count($arr);
  $powerset = array();
  
  while (count($binary) <= count($arr)) {
    $powerset[] = get_subset($binary, $arr);
    $i = 0;
    while (true) {
      if ($binary[$i]) {
        $binary[$i] = false;
        $i += 1;
      } else {
        $binary[$i] = true;
        break;
      }
    }
    $binary[$i] = true;
  }
  
  return $powerset;
}
 
print_power_sets(array());
print_power_sets(array('singleton'));
print_power_sets(array('dog', 'c', 'b', 'a'));
?>
Task: Power set






PHP: <?php
function get_subset($binary, $arr) {


  $subset = array();
  foreach (range(0, count($arr)-1) as $i) {
    if ($binary[$i]) {
      $subset[] = $arr[count($arr) - $i - 1];
    } 
  }
  return $subset;
}

function print_array($arr) {
  if (count($arr) > 0) {
    echo join(" ", $arr);
  } else {
    echo "(empty)";
  }
  echo '<br>';
}

function print_power_sets($arr) {
  echo "POWER SET of [" . join(", ", $arr) . "]<br>";
  foreach (power_set($arr) as $subset) {
    print_array($subset);
  }
}
  
function power_set($arr) {  
  $binary = array();
  foreach (range(1, count($arr)) as $i) {
    $binary[] = false;
  }
  $n = count($arr);
  $powerset = array();
  
  while (count($binary) <= count($arr)) {
    $powerset[] = get_subset($binary, $arr);
    $i = 0;
    while (true) {
      if ($binary[$i]) {
        $binary[$i] = false;
        $i += 1;
      } else {
        $binary[$i] = true;
        break;
      }
    }
    $binary[$i] = true;
  }
  
  return $powerset;
}
 
print_power_sets(array());
print_power_sets(array('singleton'));
print_power_sets(array('dog', 'c', 'b', 'a'));
?>






Ada: with Ada.Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Command_Line;
 
procedure powerset is
begin
	for set in 0..2**Argument_Count-1 loop
		Put ("{");			
		declare
			k : natural := set;
			first : boolean := true;
		begin
			for i in 1..Argument_Count loop
				if k mod 2 = 1 then
					Put ((if first then "" else ",") & Argument (i));
					first := false;
			  	end if;
				k := k / 2; 
			end loop;
		end;
		Put_Line("}");
	end loop;
end powerset;
Task: Hamming numbers

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

typedef unsigned long long ham;

size_t alloc = 0, n = 1;
ham *q = 0;

void qpush(ham h)
{
	int i, j;
	if (alloc <= n) {
		alloc = alloc ? alloc * 2 : 16;
		q = realloc(q, sizeof(ham) * alloc);
	}

	for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j);
	q[i] = h;
}

ham qpop()
{
	int i, j;
	ham r, t;
	
	for (r = q[1]; n > 1 && r == q[1]; q[i] = t) {
		
		for (i = 1, t = q[--n]; (j = i * 2) < n;) {
			if (j + 1 < n && q[j] > q[j+1]) j++;
			if (t <= q[j]) break;
			q[i] = q[j], i = j;
		}
	}

	return r;
}

int main()
{
	int i;
	ham h;

	for (qpush(i = 1); i <= 1691; i++) {
		
		h = qpop();
		qpush(h * 2);
		qpush(h * 3);
		qpush(h * 5);

		if (i <= 20 || i == 1691)
			printf("%6d: %llu\n", i, h);
	}

	
	return 0;
}
Task: Hamming numbers



C#: using System;
using System.Numerics;
using System.Linq;

namespace Hamming {

    class MainClass {

        public static BigInteger Hamming(int n) {
            BigInteger two = 2, three = 3, five = 5;
            var h = new BigInteger[n];
            h[0] = 1;
            BigInteger x2 = 2, x3 = 3, x5 = 5;
            int i = 0, j = 0, k = 0;
            
            for (int index = 1; index < n; index++) {
                h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5));
                if (h[index] == x2) x2 = two * h[++i];
                if (h[index] == x3) x3 = three * h[++j];
                if (h[index] == x5) x5 = five * h[++k];
            }
            return h[n - 1];
        }

        public static void Main(string[] args) {
            Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x))));
            Console.WriteLine(Hamming(1691));
            Console.WriteLine(Hamming(1000000));
        }
    }
}
Task: Hamming numbers


C++: #include <iostream>
#include <vector>




class Ham {
private:
	std::vector<unsigned int> _H, _hp, _hv, _x;
public:
	bool operator!=(const Ham& other) const {return true;}
	Ham begin() const {return *this;}
        Ham end() const {return *this;}
	unsigned int operator*() const {return _x.back();}
	Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){}
	const Ham& operator++() {
	  for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]);
	  _x.push_back(_hv[0]);
	  for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i];
	  return *this;
	}
};
Task: Hamming numbers





Java: import java.math.BigInteger;
import java.util.PriorityQueue;

final class Hamming {
    private static BigInteger THREE = BigInteger.valueOf(3);
    private static BigInteger FIVE = BigInteger.valueOf(5);

    private static void updateFrontier(BigInteger x,
                                       PriorityQueue<BigInteger> pq) {
        pq.offer(x.shiftLeft(1));
        pq.offer(x.multiply(THREE));
        pq.offer(x.multiply(FIVE));
    }

    public static BigInteger hamming(int n) {
        if (n <= 0)
            throw new IllegalArgumentException("Invalid parameter");
        PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>();
        updateFrontier(BigInteger.ONE, frontier);
        BigInteger lowest = BigInteger.ONE;
        for (int i = 1; i < n; i++) {
            lowest = frontier.poll();
            while (frontier.peek().equals(lowest))
                frontier.poll();
            updateFrontier(lowest, frontier);
        }
        return lowest;
    }

    public static void main(String[] args) {
        System.out.print("Hamming(1 .. 20) =");
        for (int i = 1; i < 21; i++)
             System.out.print(" " + hamming(i));
        System.out.println("\nHamming(1691) = " + hamming(1691));
        System.out.println("Hamming(1000000) = " + hamming(1000000));
    }
}
Task: Hamming numbers







Python: from itertools import islice

def hamming2():
    
    h = 1
    _h=[h]    
    multipliers  = (2, 3, 5)
    multindeces  = [0 for i in multipliers] 
    multvalues   = [x * _h[i] for x,i in zip(multipliers, multindeces)]
    yield h
    while True:
        h = min(multvalues)
        _h.append(h)
        for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)):
            if v == h:
                i += 1
                multindeces[n] = i
                multvalues[n]  = x * _h[i]
        
        mini = min(multindeces)
        if mini >= 1000:
            del _h[:mini]
            multindeces = [i - mini for i in multindeces]
        
        yield h
Task: Hamming numbers




Go: package main

import (
    "fmt"
    "math/big"
)

func min(a, b *big.Int) *big.Int {
    if a.Cmp(b) < 0 {
        return a
    }
    return b
}

func hamming(n int) []*big.Int {
    h := make([]*big.Int, n)
    h[0] = big.NewInt(1)
    two, three, five    := big.NewInt(2), big.NewInt(3), big.NewInt(5)
    next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5)
    i, j, k := 0, 0, 0
    for m := 1; m < len(h); m++ {
        h[m] = new(big.Int).Set(min(next2, min(next3, next5)))
        if h[m].Cmp(next2) == 0 { i++; next2.Mul(  two, h[i]) } 
        if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } 
        if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } 
    }
    return h
}

func main() {
    h := hamming(1e6)
    fmt.Println(h[:20])
    fmt.Println(h[1691-1])
    fmt.Println(h[len(h)-1])
}
Task: Hamming numbers



C#: using System;
using System.Numerics;
using System.Linq;

namespace Hamming {

    class MainClass {

        public static BigInteger Hamming(int n) {
            BigInteger two = 2, three = 3, five = 5;
            var h = new BigInteger[n];
            h[0] = 1;
            BigInteger x2 = 2, x3 = 3, x5 = 5;
            int i = 0, j = 0, k = 0;
            
            for (int index = 1; index < n; index++) {
                h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5));
                if (h[index] == x2) x2 = two * h[++i];
                if (h[index] == x3) x3 = three * h[++j];
                if (h[index] == x5) x5 = five * h[++k];
            }
            return h[n - 1];
        }

        public static void Main(string[] args) {
            Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x))));
            Console.WriteLine(Hamming(1691));
            Console.WriteLine(Hamming(1000000));
        }
    }
}








Fortran: program Hamming_Test
  use big_integer_module
  implicit none
  
  call Hamming(1,20)
  write(*,*)
  call Hamming(1691)
  write(*,*)
  call Hamming(1000000)
   
contains

subroutine Hamming(first, last)

  integer, intent(in) :: first
  integer, intent(in), optional :: last
  integer :: i, n, i2, i3, i5, lim
  type(big_integer), allocatable :: hnums(:)

  if(present(last)) then
    lim = last
  else
    lim = first
  end if

  if(first < 1 .or. lim > 2500000 ) then
    write(*,*) "Invalid input"
    return
  end if
  
  allocate(hnums(lim))
  
  i2 = 1 ;  i3 = 1 ; i5 = 1  
  hnums(1) = 1
  n = 1
  do while(n < lim)
    n = n + 1
    hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5))
    if(2*hnums(i2) == hnums(n)) i2 = i2 + 1
    if(3*hnums(i3) == hnums(n)) i3 = i3 + 1
    if(5*hnums(i5) == hnums(n)) i5 = i5 + 1
  end do
  
  if(present(last)) then
    do i = first, last
      call print_big(hnums(i))
      write(*, "(a)", advance="no") " "
    end do
  else
    call print_big(hnums(first))
  end if
  
  deallocate(hnums)
end subroutine
 
function mini(a, b, c)
  type(big_integer) :: mini
  type(big_integer), intent(in) :: a, b, c
   
  if(a < b ) then 
    if(a < c) then
      mini = a
    else
      mini = c
    end if
  else if(b < c) then
    mini = b
  else
    mini = c
  end if 
end function mini 
end program
Task: Hamming numbers


C++: #include <iostream>
#include <vector>




class Ham {
private:
	std::vector<unsigned int> _H, _hp, _hv, _x;
public:
	bool operator!=(const Ham& other) const {return true;}
	Ham begin() const {return *this;}
        Ham end() const {return *this;}
	unsigned int operator*() const {return _x.back();}
	Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){}
	const Ham& operator++() {
	  for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]);
	  _x.push_back(_hv[0]);
	  for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i];
	  return *this;
	}
};









Fortran: program Hamming_Test
  use big_integer_module
  implicit none
  
  call Hamming(1,20)
  write(*,*)
  call Hamming(1691)
  write(*,*)
  call Hamming(1000000)
   
contains

subroutine Hamming(first, last)

  integer, intent(in) :: first
  integer, intent(in), optional :: last
  integer :: i, n, i2, i3, i5, lim
  type(big_integer), allocatable :: hnums(:)

  if(present(last)) then
    lim = last
  else
    lim = first
  end if

  if(first < 1 .or. lim > 2500000 ) then
    write(*,*) "Invalid input"
    return
  end if
  
  allocate(hnums(lim))
  
  i2 = 1 ;  i3 = 1 ; i5 = 1  
  hnums(1) = 1
  n = 1
  do while(n < lim)
    n = n + 1
    hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5))
    if(2*hnums(i2) == hnums(n)) i2 = i2 + 1
    if(3*hnums(i3) == hnums(n)) i3 = i3 + 1
    if(5*hnums(i5) == hnums(n)) i5 = i5 + 1
  end do
  
  if(present(last)) then
    do i = first, last
      call print_big(hnums(i))
      write(*, "(a)", advance="no") " "
    end do
  else
    call print_big(hnums(first))
  end if
  
  deallocate(hnums)
end subroutine
 
function mini(a, b, c)
  type(big_integer) :: mini
  type(big_integer), intent(in) :: a, b, c
   
  if(a < b ) then 
    if(a < c) then
      mini = a
    else
      mini = c
    end if
  else if(b < c) then
    mini = b
  else
    mini = c
  end if 
end function mini 
end program
Task: Hamming numbers

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

typedef unsigned long long ham;

size_t alloc = 0, n = 1;
ham *q = 0;

void qpush(ham h)
{
	int i, j;
	if (alloc <= n) {
		alloc = alloc ? alloc * 2 : 16;
		q = realloc(q, sizeof(ham) * alloc);
	}

	for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j);
	q[i] = h;
}

ham qpop()
{
	int i, j;
	ham r, t;
	
	for (r = q[1]; n > 1 && r == q[1]; q[i] = t) {
		
		for (i = 1, t = q[--n]; (j = i * 2) < n;) {
			if (j + 1 < n && q[j] > q[j+1]) j++;
			if (t <= q[j]) break;
			q[i] = q[j], i = j;
		}
	}

	return r;
}

int main()
{
	int i;
	ham h;

	for (qpush(i = 1); i <= 1691; i++) {
		
		h = qpop();
		qpush(h * 2);
		qpush(h * 3);
		qpush(h * 5);

		if (i <= 20 || i == 1691)
			printf("%6d: %llu\n", i, h);
	}

	
	return 0;
}










Fortran: program Hamming_Test
  use big_integer_module
  implicit none
  
  call Hamming(1,20)
  write(*,*)
  call Hamming(1691)
  write(*,*)
  call Hamming(1000000)
   
contains

subroutine Hamming(first, last)

  integer, intent(in) :: first
  integer, intent(in), optional :: last
  integer :: i, n, i2, i3, i5, lim
  type(big_integer), allocatable :: hnums(:)

  if(present(last)) then
    lim = last
  else
    lim = first
  end if

  if(first < 1 .or. lim > 2500000 ) then
    write(*,*) "Invalid input"
    return
  end if
  
  allocate(hnums(lim))
  
  i2 = 1 ;  i3 = 1 ; i5 = 1  
  hnums(1) = 1
  n = 1
  do while(n < lim)
    n = n + 1
    hnums(n) = mini(2*hnums(i2), 3*hnums(i3), 5*hnums(i5))
    if(2*hnums(i2) == hnums(n)) i2 = i2 + 1
    if(3*hnums(i3) == hnums(n)) i3 = i3 + 1
    if(5*hnums(i5) == hnums(n)) i5 = i5 + 1
  end do
  
  if(present(last)) then
    do i = first, last
      call print_big(hnums(i))
      write(*, "(a)", advance="no") " "
    end do
  else
    call print_big(hnums(first))
  end if
  
  deallocate(hnums)
end subroutine
 
function mini(a, b, c)
  type(big_integer) :: mini
  type(big_integer), intent(in) :: a, b, c
   
  if(a < b ) then 
    if(a < c) then
      mini = a
    else
      mini = c
    end if
  else if(b < c) then
    mini = b
  else
    mini = c
  end if 
end function mini 
end program