go 求水仙花数,质数,字符个数

package main

import(
	"fmt"	
)

func justify(n int) bool{
	if n <=1{
		return false
	}
	for i:=2;i<n;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{
		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)
		}
	}
}

func calc(str string)(charCount int,numCount int, spaceCount int,otherCount int){
	utfChars := []rune(str)
	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()
}

输出:

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
[153] is 水仙花数哈哈
[153] is 水仙花数
[370] is 水仙花数哈哈
[370] is 水仙花数
[371] is 水仙花数哈哈
[371] is 水仙花数
[407] is 水仙花数哈哈
[407] is 水仙花数
char count:8 num count:4 sp count:9 other count:3
posted @ 2022-04-29 23:36  ty1539  阅读(25)  评论(0编辑  收藏  举报