【问题标题】:find first 1500 natural numbers whose factors are either ONLY 2, 3, or 5找出前 1500 个因数只有 2、3 或 5 的自然数
【发布时间】:2016-05-01 03:11:12
【问题描述】:

我试过了:

static void primeFactors(int n)
        {
            int t = 0;
            List<int> lst = new List<int>();

            for (int c = 2; c <= n; c = c + 1)
            {
                t = c;
                if (t % 2 == 0 || t % 3 == 0 || t % 5 == 0)
                {
                    Console.Write("{0} : ", t);
                    while (t % 2 == 0)
                    {
                            Console.Write("{0} ", 2);
                        t = t / 2;
                    }


                    for (int i = 3; i <= Math.Sqrt(t); i = i + 2)
                    {
                        while (t % i == 0)
                        {
                            Console.Write("{0} ", i);
                            t = t / i;
                        }
                    }

                    if (t >2)
                        Console.Write("{0}", t);
                    Console.WriteLine();
                }
            }
        }

我的输出:

2 : 2
3 : 3
4 : 2 2
5 : 5
6 : 2 3
8 : 2 2 2
9 : 3 3
10 : 2 5
12 : 2 2 3
14 : 2 7 ** should not be list 
15 : 3 5
16 : 2 2 2 2
18 : 2 3 3
20 : 2 2 5
21 : 3 7  ** should not be list 
22 : 2 11  ** should not be list 
24 : 2 2 2 3
25 : 5 5
26 : 2 13  ** should not be list 
27 : 3 3 3
28 : 2 2 7  ** should not be list 
30 : 2 3 5

所需的输出: 前 20 个数字是(分号后列出的因素):

2 : 2

3 : 3

4 : 2 2 

5 : 5

6 : 2 3

8 : 2 2 2 

9 : 3 3 

10 : 2 5

12 : 2 2 3

15 : 3 5

16 : 2 2 2 2 

18 : 2 3 3 

20 : 2 2 5

24 : 2 2 2 3

25 : 5 5 

27 : 3 3 3 

30 : 2 3 5

32 : 2 2 2 2 2 

36 : 2 2 3 3 

40 : 2 2 2 5

注意:14(2*7),21 (3*7), 22 (2*11), 26 (2*13) 是不应出现在列表中的数字。因子只能是 2、3 或 5

【问题讨论】:

  • 都是不同的语言,先决定你想要的代码是哪种语言?
  • 我需要 vb /c#
  • 只有 2、3、5 作为因数的自然数...是三个与其他一个或自身的倍数......请将标签更改为这些语言。
  • 所以选择这两种语言中的一种,然后删除剩余的标签垃圾邮件。

标签: c#


【解决方案1】:

考虑这个问题的一种方法是说把数字x 传递给过滤器(实际上你已经在你的代码中开始这样做了)。第一个过滤器会说“当数字可被 2 整除时,继续将其除以 2”。第二个过滤器对 3 说同样的事情,第三个过滤器对 5 说同样的事情。最后你检查你剩下的是否等于 1。如果是,它没有更多的因素。这里有一些伪代码可以帮忙:

function isDivisible(t) {
    while (t % 2 == 0) {
        t = t / 2;
    }
    while (t % 3 == 0) {
        t = t / 3;
    }
    while (t % 5 == 0) {
        t = t / 5;
    }
    return t == 1;
}

可能值得注意的是,这绝不是解决这个问题的最快方法;有更快的解决方案。

【讨论】:

  •  static void isDivisible(int t) { int count = 0;整数 = t;而 (num % 2 == 0) { num = num / 2; Console.Write(num); } while (num % 3 == 0) { num = num / 3; Console.Write(num); } while (num % 5 == 0) { num = num / 5; Console.Write(num); } if (num == 1) 返回 ; } 输出:对于 6 :输出是 3,1,实际上是 2,3 
  • 该代码与我的函数不同。再看一下我的代码(我测试过,它有效)。我的函数返回一个布尔值,指示一个数字是否可以被 2、3 和 5 整除
猜你喜欢
  • 2016-06-12
  • 2019-06-20
  • 2016-03-17
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
相关资源
最近更新 更多