go计算质数,水仙花数,字符串分类个数

点击查看代码
package main

import (
	"fmt"
	"math"
)

func justify(n int) bool {
	sqrtN := int(math.Sqrt(float64(n)))
	if n <= 1 {
		return false
	}
	for i := 2; i < sqrtN; i++ {
		if n%i == 0 {
			return false
		}
	}
	return true
}

func example1() {
	for i := 2; i < 100; i++ {
		if justify(i) == true {
			fmt.Printf("%d is prime\n", i)
		}
	}
}

func is_shuixianhua(n int) bool {
	first := n % 10         // 个位 %取余
	second := (n / 10) % 10 // 十位
	third := (n / 100) % 10 // 百位
	fmt.Printf("n:%d third:%d second:%d first:%d \n",n,third,second,first)
	// if n == first*first*first+second*second*second+third*third*third {
	y := float64(3)
	if float64(n) == math.Pow(float64(first), y) + math.Pow(float64(second), y) + math.Pow(float64(third), y){
		fmt.Printf("[%d] is 水仙花数哈哈\n", n)
		return true
	}
	return false
}

func example2() {
	for i := 100; i < 1000; i++ {
		if is_shuixianhua(i) {
			fmt.Printf("[%d] is 水仙花数 \n", i)
		}
	}
}
//str>> asdf    7461    ASDX 我打扫 30 utfChars [97 115 100 102 32 32 32 32 55 52 54 49 32 32 32 32 65 83 68 88 32 25105 25171 25195] 24

func calc(str string) (charCount int, numCount int, spaceCount int, otherCount int) {
	utfChars := []rune(str)
	fmt.Println("str>>",str,len(str),"utfChars",utfChars,len(utfChars))
	for i := 0; i < len(utfChars); i++ {
		if utfChars[i] >= 'a' && utfChars[i] <= 'z' || utfChars[i] >= 'A' && utfChars[i] <= 'Z' {
			charCount++
			continue
		}
		if utfChars[i] >= '0' && utfChars[i] <= '9' {
			numCount++
			continue
		}
		if utfChars[i] == ' ' {
			spaceCount++
			continue
		}
		otherCount++
	}
	return
}

func example3() {
	var str string = "asdf    7461    ASDX 我打扫"
	charCount, numCount, SpCount, other := calc(str)
	fmt.Printf("char count:%d num count:%d sp count:%d other count:%d ", charCount, numCount, SpCount, other)
}

func main() {
	example1()
	//example2()
	//example3()
}

posted @ 2022-03-06 21:46  ty1539  阅读(33)  评论(0编辑  收藏  举报