构建一个整数数组来实现特定序列 [英] construct an array of integers to achieve specific sequence

查看:112
本文介绍了构建一个整数数组来实现特定序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


结构使用以下规则以A结尾,
整数最短的序列:



的第一个元素顺序是1,每个连续
元素是任何两个前述元素的总和(添加单个
元素本身也是允许的),每个元件比
中的所有前述元件更大;即,序列在增加。



例如,对于A = 42,一个可能的解决办法是[1,2,3,6,12,24,
30,42]。另一种可能的解决方案是[1,2,4,5,8,16,21,42]。




我写了下面的但它未能对456输入,通过返回[1,2,4,8,16,32,64,128,200,256,456],有可以被加在一起以获得200的序列中没有数字



我怎么能解决下面的代码?我究竟做错了什么?



 公共静态INT []击(INT N)
{
名单,LT ; INT> NUMS =新的List< INT>();

INT X = 1;

,而(X< N)
{
nums.Add(X);
X = X * 2;

如果(X将N)
{

nums.Add(N - (X / 2));

nums.Add(N);
}
}

nums.Sort();
INT [] = ARR nums.ToArray();
返回编曲;
}


解决方案

下面是我用C解++ (有微弱改变为C#):

 无效printSequenceTo(无符号N)
{
如果( n ==可1){printf的(1);返回; }
如果(N&安培; 1){
INT因子= 3;
做{
如果(N%的因素== 0){
printSequenceTo(N /因子*(因子-1));
因子= 0;
中断;
}
+系数= 2;
},而(*因子因子VIII = N);
如果(因子)printSequenceTo(N-1);
}
,否则
printSequenceTo(N / 2);
的printf(%U,N);
}



示范:的 http://ideone.com/8lXxc



当然也可能使用分解筛子来加快。






请注意,这是对公认的答案显著的改善,但它仍然不是最佳的。


construct the shortest possible sequence of integers ending with A, using the following rules:

the first element of the sequence is 1, each of the successive elements is the sum of any two preceding elements (adding a single element to itself is also permissible), each element is larger than all the preceding elements; that is, the sequence is increasing.

For example, for A = 42, a possible solutions is [1, 2, 3, 6, 12, 24, 30, 42]. Another possible solution is [1, 2, 4, 5, 8, 16, 21, 42].

I have written the following but it fails on input of 456, by returning[1,2,4,8,16,32,64,128,200,256,456] , there are no numbers in the sequence that can be added together to get 200.

how can I fix the below code? what am I doing wrong?

  public static int[] hit(int n)
    {
        List<int> nums = new List<int>();

        int x = 1;

        while (x < n)
        {
            nums.Add(x);
            x = x * 2;

            if (x > n)
            {

                    nums.Add(n - (x / 2));

                nums.Add(n);
            }
        }

        nums.Sort();
        int[] arr =  nums.ToArray();
        return arr;
    }

解决方案

Here is my solution in C++ (may be trivially changed to C#):

void printSequenceTo(unsigned n)
{
    if (n == 1) { printf("1"); return; }
    if (n & 1) {
        int factor = 3;
        do {
            if (n % factor == 0) {
                printSequenceTo(n / factor * (factor-1));
                factor = 0;
                break;
            }
            factor += 2;
        } while (factor * factor <= n);
        if (factor) printSequenceTo(n-1);
    }
    else
        printSequenceTo(n/2);
    printf(",%u", n);
}

Demonstration: http://ideone.com/8lXxc

Naturally it could be sped up using a sieve for factorization.


Note, this is significant improvement over the accepted answer, but it still is not optimal.

这篇关于构建一个整数数组来实现特定序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆