Tìm số semiperinf nguyên thủy


17

Số bán kết

Số semiperinf / pseudoperinf là một số nguyên bằng tổng của một phần hoặc tất cả các ước của nó (không bao gồm chính nó). Các số bằng tổng của tất cả các ước của chúng là hoàn hảo.

Divisors of 6 : 1,2,3
      6 = 1+2+3 -> semiperfect (perfect)
Divisors of 28 : 1,2,4,7,14
      28 = 14+7+4+2+1 -> semiperfect (perfect)
Divisors of 40 : 1,2,4,5,8,10,20
      40 = 1+4+5+10+20 or 2+8+10+20 -> semiperfect

Nguyên thủy

Một số bán chính xác nguyên thủy là một số bán chính xác không có ước số bán chính xác (ngoại trừ chính nó :))

Divisors of 6 : 1,2,3
      6  = 1+2+3 -> primitive
Divisors of 12 : 1,2,3,4,6
      12 = 2+4+6 -> semiperfect

Để tham khảo, vui lòng sử dụng sê-ri OEIS A006036 cho các số bán chính xác nguyên thủy và A005835 cho các semiperinfs.

Mục tiêu

Viết một chương trình hoặc một chức năng trong bất kỳ ngôn ngữ. Nó sẽ lấy đầu vào là số n làm tham số hàm hoặc từ STDIN / ngôn ngữ thay thế gần nhất của ngôn ngữ của bạn và sẽ xuất tất cả các số bán hoàn hảo nguyên thủy từ 1 đến n (đã bao gồm).

Đầu ra phải được định dạng là 6[separator]20[separator]28[separator]88...nơi [dấu phân cách] là dòng mới, dấu cách hoặc dấu phẩy. Không được có [bắt đầu phân tách] cũng không phải là kết thúc.

Chỉnh sửa: bạn có thể để lại một dòng mới

Ví dụ

đầu vào :

5

đầu ra:

đầu vào :

20

đầu ra:

6
20

đầu vào :

100

đầu ra:

6 20 28 88

Chấm điểm

Đây là mã golf, vì vậy mã ngắn nhất tính bằng byte sẽ thắng.

Làm ơn đừng cố lừa chúng tôi bằng những sơ hở :).

Tôi rất vui vì bạn có thể để lại lời giải thích về mã đánh gôn của mình một khi bạn nghĩ rằng bạn đã chơi xong nó!

Vì thử thách này đã có một số câu trả lời hay và đang dần im lặng, tôi sẽ chấm dứt nó. Người chiến thắng môn đánh gôn này sẽ được quyết định vào Thứ Hai ngày 29, 00:00 GMT. Làm tốt cho tất cả các bạn đã trả lời, và chúc may mắn cho những người sẽ cố gắng đánh bại họ :)

Câu trả lời:


8

Bình thường, 28 27 byte

VQI}KhNsMyJf!%KTSNI!@JYeaYK

1 byte nhờ @Jakube

Trình diễn.

VQI}KhNsMyJf!%KTSNI!@JYeaYK
                                Implicit:
                                Y = []
                                Q = eval(input())
VQ                              for N in range(Q):
    KhN                         K = N+1
           f    SN              filter T over range(1, N)
            !%KT                the logical not of K%T.
                                This is the list of divisors of K.
          J                     Store the list in J.
         y                      Create all of its subsets.
       sM                       Map each subset to its sum.
  I}K                           If K is in that list: (If K is semiperfect)
                  I!@JY         If the intersection of J (the divisors)
                                and Y (the list of primitive semiperfect numbers)
                                is empty:
                        aYK     Append K to Y
                       e        And print its last element, K.

@AlexA. Cảm ơn! Nó là cần thiết để thêm Kvào Yđể xây dựng Y, đó là cần thiết ở những nơi khác. Tuy nhiên, tôi có thể thực hiện in riêng, chẳng hạn như aYKKthay vì eaYK. Đó là 4 byte, tuy nhiên.
isaacg

3

Julia, 161 149 byte

n->(S(m)=!isempty(filter(i->i==unique(i)&&length(i)>1&&all(j->m%j<1,i),partitions(m)));for i=2:n S(i)&&!any(S,filter(k->i%k<1,1:i-1))&&println(i)end)

Điều này tạo ra một hàm không tên, chấp nhận một số nguyên làm đầu vào và in các số thành STDOUT cách nhau bởi một dòng mới. Để gọi nó, đặt tên cho nó, vd f=n->....

Ungolfed + giải thích:

# Define a function that determines whether the input is semiperfect
# (In the submission, this is defined as a named inline function within the
# primary function. I've separated it here for clarity.)

function S(m)
    # Get all integer arrays which sum to m
    p = partitions(m)

    # Filter the partitions to subsets of the divisors of m
    d = filter(i -> i == unique(i) && length(i) > 1 && all(j -> m % j == 0, i), p)

    # If d is nonempty, the input is semiperfect
    !isempty(d)
end

# The main function

function f(n)
    # Loop through all integers from 2 to n
    for i = 2:n
        # Determine whether i is semiperfect
        if S(i)
            # If no divisors of i are semiperfect, print i
            !any(S, filter(k -> i % k == 0, 1:i-1) && println(i)
        end
    end
end

Ví dụ:

julia> f(5)

julia> f(40)
6
20
28

3

JavaScript ( ES6 ) 172

Chạy đoạn mã dưới đây để kiểm tra

f=
v=>eval("for(n=h=[];n++<v;!t*i&&n>1?h[n]=1:0){for(r=[l=i=t=1];++i<n;)n%i||(h[i]?t=0:l=r.push(i));for(i=0;t&&++i<1<<l;)r.map(v=>i&(m+=m)?t-=v:0,t=n,m=.5)}''+Object.keys(h)")


// Less golfed

ff=v=>
{
   h=[]; // hashtable with numbers found so far

   for (n=1; n <= v; n++)
   {
      r=[1],l=1; // r is the list of divisors, l is the length of this list
      t=1; // used as a flag, will become 0 if a divisor is in h
      for(i=2; i<n; i++)
      {
         if (n%i == 0)
            if (h[i])
               t = 0; // found a divisor in h, n is not primitive
            else
               l = r.push(i); // add divisor to r and adjust l
      }
      if (t != 0) // this 'if' is merged with the for below in golfed code
      { 
         // try all the sums, use a bit mask to find combinations
         for(i = 1; t != 0 && i < 1<<l; i++)
         {
            t = n; // start with n and subtract, if ok result will be 0 
            m = 0.5; // start with mask 1/2 (nice that in Javascript we can mix int and floats)
            r.forEach( v=> i & (m+=m) ? t -= v : 0);
         }
         if (t == 0 && n > 1) h[n] = 1; // add n to the hashmap (the value can be anything)
      }
   }
   // the hashmap keys list is the result
   return '' + Object.keys(h) // convert to string, adding commas
}

(test=()=> O.textContent=f(+I.value))();
<input id=I type=number oninput="test()" value=999><pre id=O></pre>


@ JörgHülsermann đã hoàn thành, cảm ơn vì đã chú ý
edc65

2

CJam, 54 byte

Giải pháp này cảm thấy hơi khó xử, nhưng vì đã có một vài câu trả lời, và không có câu trả lời nào trong CJam, tôi nghĩ rằng dù sao tôi cũng sẽ đăng nó:

Lli),2>{_N,1>{N\%!},_@&!\_,2,m*\f{.*:+}N#)e&{N+}&}fNS*

Một phần tốt của sự gia tăng so với giải pháp Pyth được đăng xuất phát từ thực tế là, theo như tôi có thể tìm thấy, CJam không có toán tử để liệt kê tất cả các tập con của một tập hợp. Vì vậy, phải mất một số công việc để hoàn thành điều đó với các nhà khai thác có sẵn. Tất nhiên, nếu thực sự có một toán tử đơn giản mà tôi đã bỏ lỡ, tôi sẽ trông thật ngớ ngẩn. :)

Giải trình:

L     Start stack with empty list that will become list of solutions.
li    Get input N and convert to int.
),2>  Build list of candidate solutions [2 .. N].
{     Start for loop over all candidate solutions.
_     Copy list of previous solutions, needed later to check for candidate being primitive.
N,1>  Build list of possible divisors [1 .. N-1].
{N\%!},  Filter list to only contain actual divisors of N.
_     Check if one of divisors is a previous solution. Start by copying divisor list.
@     Pull copy of list with previous solutions to top of stack
&!    Intersect the two lists, and check the result for empty. Will be used later.
\     Swap top two elements, getting divisor list back to top.
_,    Get length of divisor list.
2,    Put [0 1] on top of stack.
m*    Cartesian power. Creates all 0/1 sequences with same length as divisor list.
\     Swap with divisor list.
f{.*:+}  Calculate element by element product of all 0/1 sequences with divisors,
         and sum up the values (i.e. dot products of 0/1 sequences with divisors).
         The result is an array with all possible divisor sums.
N#)  Find N in list of divisor sums, and covert to truth value.
e&   Logical and with earlier result from primitive test.
{N+}&  Add N to list of solutions if result is true.
}fN  Phew! We finally made it to the end of the for loop, and have a list of solutions.
S*   Join the list of solutions with spaces in between.

Dùng thử trực tuyến


2

PHP, 263 byte

function m($a,$n){for($t=1,$b=2**count($a);--$b*$t;$t*=$r!=$n,$r=0)foreach($a as$k=>$v)$r+=($b>>$k&1)*$v;return$t;}for($o=[];$i++<$argn;m($d,$i)?:$o=array_merge($o,range($r[]=$i,3*$argn,$i)))for($d=[],$n=$i;--$n*!in_array($i,$o);)$i%$n?:$d[]=$n;echo join(",",$r);

Hãy thử trực tuyến!

Mở rộng

function m($a,$n){ 
  for($t=1,$b=2**count($a);--$b*$t;$t*=$r!=$n,$r=0) #loop through bitmasks
    foreach($a as$k=>$v)$r+=($b>>$k&1)*$v; # loop through divisor array
  return$t;} # returns false for semiperfect numbers 
for($o=[];$i++<$argn;
m($d,$i)?
  :$o=array_merge($o,range($r[]=$i,3*$argn,$i))) # Make the result array and the array of multiples of the result array 
  for($d=[],$n=$i;--$n*!in_array($i,$o);) # check if integer is not in multiples array
    $i%$n?:$d[]=$n; # make divisor array
echo join(",",$r); #Output

1

Thạch , 22 byte

ÆDṖŒPS€i
ÆDÇ€TL’
RÇÐḟY

Hãy thử trực tuyến!

Giải trình

ÆDṖŒPS€i - helper function to check if input is a semiperfect number
ÆD       - list of divisors of input
  Ṗ      - except for the last one (the input)
   ŒP    - power set = every possible subset of divisors
     S€  - sum of each subset
       i - return truthy iff input is one of these

ÆDÇ€TL’ - helper function to check if input is a primitive semiperfect number
ÆD       - list of divisors of input
  ǀ     - replace each with if they are a semiperfect number, based on 
           the above helper function. If input is a primitive semiperfect 
           number, we get something like [0,0,0,0,0,94]. 
    T    - get all truthy values.
     L’  - return falsy iff there is only one truthy value

RÇÐḟY    - main link
R        - Range[input]
 ÇÐḟ     - Filter out those elements which are not primitive semiperfect
           numbers, based on the helper function
    Y    - join by newlines.
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.