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

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

作者: masakakaikai | 来源:发表于2015-09-18 10:31 被阅读175次

    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);}}
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/gxmbcttx.html