Go语言学习笔记九--Go语言练习--判断素数(质数)--水仙花数--统计字符

一、判断素数(质数)

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "math"
 6 )
 7 //判断是否是质数
 8 func isParam(num int) bool {
 9     if num < 1 {
10         return false
11     }
12     sqrt :=  int(math.Sqrt(float64(num)))
13 
14     for i := 2; i <= sqrt; i++ {
15         if num % i == 0 {
16             return false
17         }
18     }
19     return true
20 }
21 //输出质数
22 func printParam(num int)  {
23     fmt.Printf("%d 以内的质数为:",num)
24     for i := 2; i < num ; i++ {
25         if isParam(i) {
26             fmt.Printf("%d ", i)
27         }
28     }
29 }
30 
31 func main() {33     printParam(100)
34 }

二、水仙花数

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "math"
 6 )
 7 //水仙花数
 8 func printFlower(){
 9     for i := 100; i < 999; i++ {
10         g := i%10 //计算个位
11         b := i/100  //计算百位
12         s := (i-b*100)/10  //计算十位
13         if i == (g*g*g + s*s*s + b*b*b) {
14             fmt.Printf("%d is flower number
", i)
15         }
16     }
17 }
18 
19 
20 func main() {
21     fmt.Println("100-1000里面的水仙花数为:")
22     printFlower()
23 }

三、统计字符

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "math"
 6 )
 7 
 8 //统计字符个数
 9 func countChar(str string) {
10     var count [256]int
11     for i := 0 ;i < len(str); i++ {
12         count[str[i]]++
13     }
14     for i := 0 ;i < 128; i++ {
15         fmt.Printf("%c : %d
",i,count[i])
16     }
17 }
18 //统计字符个数
19 func countChar2(str string) {
20     var (
21         shuzi, zifu, other = 0,0,0
22     )
23 
24     for i := 0 ;i < len(str); i++ {
25         if str[i]>='0' && str[i] <= '9' {
26             shuzi++
27         } else if str[i]>='a' && str[i] <= 'z'{
28             zifu++
29         } else if str[i]>='A' && str[i] <= 'Z'{
30             zifu++
31         } else {
32             other++
33         }
34     }
35     fmt.Printf("数字:%d , 字符:%d ,其他:%d
",shuzi,zifu,other)
36 }
37 
38 func main() {
39     fmt.Println("统计字符:")
40     str := "qwsdjabdhjabwuieda!@#!#!@##$#%^&**(()&(2131321423424DSFSF{}|L:,/.']sdamnbvczxlouey-=1231@!#"
41     countChar2(str)
42     //countChar(str)
43 }
原文地址:https://www.cnblogs.com/xwxz/p/13303993.html