java Ex1.1.24

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Ex1.1.24相关的知识,希望对你有一定的参考价值。

def gcd(p: int, q: int, level: int) -> int:
    # 打印递归深度
    print("{:s}p: {:d}  q: {:d}  level: {:d}".format(
        "    " * level, p, q, level))
    if p <= 0 or q <= 0:
        return -1
    if p % q == 0:
        return q
    else:
        return gcd(q, p % q, level+1)


def gcd2(p: int, q: int) -> int:
    if p <= 0 or q <= 0:
        return -1
    tmp = p % q
    while tmp != 0:
        p = q
        q = tmp
        tmp = p % q
    return q


if __name__ == '__main__':
    print(gcd(33, 22, 0))
    print(gcd2(33, 22))
package main

import "fmt"

func main() {
    fmt.Println(gcd(33, 22, 0))
    fmt.Println(gcd2(33, 22))
}

func gcd(p, q, level int) int {
    // 打印递归深度
    for i := 0; i < level; i++ {
        fmt.Print("    ")
    }
    fmt.Printf("p: %d  q: %d  level: %d\n", p, q, level)
    if q <= 0 || p <= 0 {
        return -1
    }
    if p%q == 0 {
        return q
    }
    return gcd(q, p%q, level+1)
}

func gcd2(p, q int) int {
    if q <= 0 || p <= 0 {
        return -1
    }
    tmp := p % q
    for tmp != 0 {
        p = q
        q = tmp
        tmp = p % q
    }
    return q
}
package com.test;


public class Gcd {
    public static void main(String[] args) {
//        System.out.println(gcd(1111111, 1234567, 0));
        System.out.println(gcd(33, 22));
    }

    private static int gcd(int p, int q) {
        if (p <= 0 || q <= 0 ){
            return -1;
        } 
        int tmp = p % q;
        while (tmp != 0) {
            p = q;
            q = tmp;
            tmp = p % q;
        }
        return q;
    }

    private static int gcd(int p, int q, int level) {
        // 打印递归深度
        for (int i = 0; i < level; i++) {
            System.out.print("    ");
        }
        System.out.printf("p: %d  q: %d  level:%d\n", p, q, level);
        if (p <= 0 || q <= 0 ){
            return -1;
        }    
        if (p % q == 0) {
            return q;
        }
        return gcd(q, p % q, level + 1);
    }
}

以上是关于java Ex1.1.24的主要内容,如果未能解决你的问题,请参考以下文章

Java Math

Java 布尔运算

java [Java] Java常用代码#java

Java - 35 Java 实例

Java While 循环

Java 字符串