码迷,mamicode.com
首页 > 编程语言 > 详细

Java小例子——穷举质数,求平方和,求质因子。

时间:2014-06-11 09:36:52      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   java   com   string   

求平方和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public static void main(String[] args) throws IOException
    {
        int n;
        String s;
        BufferedReader buf;
 
        buf=new BufferedReader(new InputStreamReader(System.in));
 
        System.out.print("请输入一个自然数:");
        s=buf.readLine();
        n=Integer.parseInt(s);
 
        System.out.print("f(n)=1");
        for(int i=2;i<=n;i++)
            System.out.print("+"+i*i);
        System.out.print("="+Square(n));
 
    }
 
    public static long Square(int n)
    {
        long f=0;
        if(n<0)
            System.out.println("n<0,输入错误!");
        else if
            (n==1)f=1;
        else
            f=Square(n-1)+n*n;
        return f;
    }

 穷举质数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String args[])
    {
        int i,j;
        for(j=2;;j++) 
        {
            for(i=2;i<=j/2;i++)
            {
                if(j%i==0)
                    break;
            }
            if(i>j/2
            {
                System.out.println(j);
            }
        }
    }

 求质因子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public static void main(String[] args)
    {
        int n = 0;
        String s = null;
        BufferedReader buf;
        buf=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("请输入一个数:");
        try {
            s=buf.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        n=Integer.parseInt(s);
        int temp = n;
        for (int i = 2; i <= temp; i++)
        {
            if (!isPrime(i))
            {
                continue;
            }
            while (true)
            {
                if (temp%i == 0)
                {
                    temp = temp/i;
                    System.out.println(i);
                }
                else {
                    break;
                }
            }
        }
    }
    public static boolean isPrime(int n)
    {
        int i;
        for (i = 2; i <= n; i++)
        {
            if (n%i == 0)
            {
                break;
            }
        }
        if (i >= n)
        {
            return true;
        }
        else {
            return false;
        }
    }

 

Java小例子——穷举质数,求平方和,求质因子。,布布扣,bubuko.com

Java小例子——穷举质数,求平方和,求质因子。

标签:class   blog   code   java   com   string   

原文地址:http://www.cnblogs.com/zmrid/p/3773012.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!