简书的代码高亮展示(夜间阅读模式)——to刘mingxing

2015-09-18  本文已影响175人  masakakaikai

c

#include<stdio.h>
int gcd(long a,long b);
 
int main(){
    int a,b;
    printf("Enter 2 numbers:");
    scanf("%d%d",&a,&b);
    printf("Greatest Common Divisor is %d",gcd(a,b));
    return 0; 
}

int gcd(long a,long b)
{
if(b==0)
  return a;
else
  return gcd(b,a%b);
}//递归,辗转相除

c++

void move(int n, int from, int to, int via) 
{
    if (n == 1) 
    {std::cout << "Move disk from pole " 
<< from << " to pole " << to << std::endl;} 
    else {move(n - 1, from, via, to);
    move(1, from, to, via);
    move(n - 1, via, to, from);}}

java

public void move(int n, int from, int to, int via) {
  if (n == 1) {
    System.out.println("Move disk from pole " + from + " to pole " + to);
  } else {
    move(n - 1, from, via, to);
    move(1, from, to, via);
    move(n - 1, via, to, from);
  }
}

python

def hanoi(ndisks, startPeg=1, endPeg=3):
    if ndisks:
        hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
        print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
        hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)
 
hanoi(ndisks=4)

ruby

def move(num_disks, start=0, target=1, using=2)
  if num_disks == 1
   @towers[target] << @towers[start].pop
    puts "Move disk from #{start} to #{target} : #{@towers}"
  else
    move(num_disks-1, start, using, target)
    move(1,           start, target, using)
    move(num_disks-1, using, target, start)
  end 
end
 
n = 5
@towers = [[*1..n].reverse, [], []]
move(n)

php

function move($n,$from,$to,$via) 
{if ($n === 1) 
{print("Move disk from pole $from to pole $to");} 
else {move($n-1,$from,$via,$to);
move(1,$from,$to,$via);
move($n-1,$via,$to,$from);}}
上一篇下一篇

猜你喜欢

热点阅读