我是否完美(数字)?


26

这是我的第一个挑战!

背景

完美数是一个正整数,等于除其本身以外所有除数的总和。
因此6,完美数是1 + 2 + 3 = 6
另一方面12不是,因为1 + 2 + 3 + 4 + 6 = 16 != 12

任务

您的任务很简单,编写一个程序,对于给定的程序,将n打印以下消息之一:

我是一个完美的数字,因为d1 + d2 + ... + dm = s == n
我不是一个完美的数字,因为d1 + d2 + ... + dm = s [<>] n

除的
d1, ... dm所有除数都在哪里?是所有除数的总和(再次,不带)。是(if )或(if )。nn
sd1, ..., dmn
[<>]<s < n>s > n

例子

n6: “我是完全数,因为1 + 2 + 3 = 6 == 6”
n12: “我是不是一个完美的数目,因为1 + 2 + 3 + 4 + 6 = 16> 12”
n存在13:“我不是一个完美的数字,因为1 = 1 <13”

规则

  • n不大于您的语言的标准int
  • 您可以n从标准输入,命令行参数或文件中读取。
  • 输出消息必须打印在标准输出上,并且输出中不能出现其他字符(它可能带有尾随空格或换行符)
  • 您不得使用任何内置或库函数来为您解决任务(或其主要部分)。否GetDivisors()或类似的内容。
  • 所有其他标准漏洞均适用。

优胜者

这是因此以字节为单位的最短代码胜出!


@orlp不是,我编辑了挑战,谢谢。
Zereges

7
为什么在相同的方程式中使用===?这是没有意义的。应该是d1 + d2 + ... + dm = s = nIMO。
orlp

您能否提供一些输入和输出示例,例如输入6和12?
Zgarb 2015年

14
@Zereges这是荒谬的。没有任何分配。仅比较。
orlp

1
@orlp是有意的。
Zereges

Answers:


4

Pyth,81个字节

jd[+WK-QsJf!%QTStQ"I am"" not""a perfect number, because"j" + "J\=sJ@c3"==<>"._KQ

在线尝试:演示测试套件

说明:

                                 implicit: Q = input number
               StQ               the range of numbers [1, 2, ..., Q-1]
          f                      filter for numbers T, which satisfy:
           !%QT                     Q mod T != 0
         J                       save this list of divisors in J
      -QsJ                       difference between Q and sum of J
     K                           save the difference in K

jd[                              put all of the following items in a list
                                 and print them joined by spaces: 
                  "I am"           * "I am"
   +WK                  " not"       + "not" if K != 0
"a perfect number, because"        * "a perfect ..."
j" + "J                            * the divisors J joined by " + "
       \=                          * "="
         sJ                        * sum of J
            c3"==<>"               * split the string "==<>" in 3 pieces:
                                        ["==", "<", ">"]
           @        ._K              and take the (sign of K)th one (modulo 3)
                       Q           * Q

9

Java中,255个 270字节(静止FF在基体17)

class C{public static void main(String[]a){int i=new Integer(a[0]),k=0,l=0;a[0]=" ";for(;++k<i;)if(i%k<1){l+=k;a[0]+=k+" ";}}System.out.print("I am "+(l==i?"":"not ")+"a perfect number, because "+a[0].trim().replace(" "," + ")+" = "+l+(l==i?" == ":l<i?" < ":" > ")+i);}}

以及更具可读性的版本:

class C {
    public static void main(String[] a) {
        int i = new Integer(a[0]), k = 0, l = 0;
        a[0] = " ";
        for(; ++k<i ;){
            if (i % k == 0) {
                l += k;
                a[0] += k + " ";
            }
        }
        System.out.print("I am " + (l == i ? "" : "not ") + "a perfect number, because " + a[0].trim().replace(" "," + ") + " = " + l + (l == i ? " == " : l < i ? " < " : " > ") + i);
    }
}

以前不适用于奇数,所以我不得不调整一些东西。至少我再次幸运地得到了字节数。:)


我会工作超过255吗?
dwana 2015年

我知道,如果你的废墟字节数,但你可以通过用“串B”和使用“B”在他们的地方将最后(四)的[0]出现三个存储字符
克雷格

6

R,158个 163 157 153 143 141字节

我认为仍然有打高尔夫球的空间。
编辑:替换if(b<n)'<'else if(b>n)'>'else'=='c('<'[b<n],'>'[b>n],'=='[b==n])。将paste(...)替换为rbind(...)[-1]。感谢@plannapus多了两个字节。

n=scan();a=2:n-1;b=sum(w<-a[!n%%a]);cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)

不打高尔夫球

n<-scan()             # get number from stdin
w<-which(!n%%1:(n-1)) # build vector of divisors
b=sum(w)              # sum divisors
cat('I am',           # output to STDOUT with a space separator
    'not'[b!=n],      # include not if b!=n
    'a perfect number, because',
    rbind('+',w)[-1], # create a matrix with the top row as '+', remove the first element of the vector
    '=',
    b,                # the summed value
    c(                # creates a vector that contains only the required symbol and ==
        '<'[b<n],     # include < if b<n
        '>'[b>n],     # include > if b>n
        '=='
    )[1],             # take the first element 
    n                 # the original number
)

测试运行

> n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)
1: 6
2: 
Read 1 item
I am a perfect number, because 1 + 2 + 3 = 6 == 6
> n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)
1: 12
2: 
Read 1 item
I am not a perfect number, because 1 + 2 + 3 + 4 + 6 = 16 > 12
> n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)
1: 13
2: 
Read 1 item
I am not a perfect number, because 1 = 1 < 13
> 

+除数之间应有符号。
Zereges

@Zereges我刚刚注意到,它将很快修复
MickyT 2015年

+1为绝妙rbind绝招!如果分配2:n-1给变量,您可以节省2个额外的字节,例如awhich(!n%%1:(n-1)) 成为a[!n%%a]。(然后是完整的代码n=scan();a=2:n-1;b=sum(w<-a[!n%%a]);cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)
plannapus 2015年

@plannapus谢谢,我对此感到非常满意。
MickyT

5

Python 2中,183个 173 170字节

b=input();c=[i for i in range(1,b)if b%i<1];d=sum(c);print'I am %sa perfect number because %s = %d %s %d'%('not '*(d!=b),' + '.join(map(str,c)),d,'=<>='[cmp(b,d)%3::3],b)

例子:

$ python perfect_number.py <<< 6
I am a perfect number because 1 + 2 + 3 = 6 == 6
$ python perfect_number.py <<< 12
I am not a perfect number because 1 + 2 + 3 + 4 + 6 = 16 > 12
$ python perfect_number.py <<< 13
I am not a perfect number because 1 = 1 < 13
$ python perfect_number.py <<< 100
I am not a perfect number because 1 + 2 + 4 + 5 + 10 + 20 + 25 + 50 = 117 > 100
$ python perfect_number.py <<< 8128
I am a perfect number because 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 = 8128 == 8128

感谢xnor节省了13个字节!


4
'=<>'[cmp(b,d)]-加入革命!
orlp

太好了,谢谢!哦,等等... :)
Celeo

1
@Celeo我想出了一个类似的解决方案。你可以写b%i<1b%i==0。对于['not ',''][int(d==b)],您不需要int,因为Python会自动转换。此外,您可以使用字符串mulitplication "not "*(d!=b)
xnor

@xnor感谢您的建议!
Celeo 2015年

1
@Celeo您可以调整orlp的建议以使其工作"=<>="[cmp(b,d)%3::3]
xnor

4

朱莉娅161个 157字节

n=int(ARGS[1])
d=filter(i->n%i<1,1:n-1)
s=sum(d)
print("I am ",s!=n?"not ":"","a perfect number, because ",join(d," + ")," = $s ",s<n?"<":s>n?">":"=="," $n")

取消高尔夫:

# Read n as the first command line argument
n = int(ARGS[1])

# Get the divisors of n and their sum
d = filter(i -> n % i == 0, 1:n-1)
s = sum(d)

# Print to STDOUT
print("I am ",
      s != n ? "not " : "",
      "a perfect number, because ",
      join(d, " + "),
      " = $s ",
      s < n ? "<" : s > n ? ">" : "==",
      " $n")

4

CJam,90个字节

"I am"rd:R{R\%!},:D:+R-g:Cz" not"*" a perfect number, because "D'+*'=+D:++'=C+_'=a&+a+R+S*

为了进行比较,=可以以83个字节来打印单个。

CJam解释器中在线尝试。

怎么运行的

"I am"  e# Push that string.
rd:R    e# Read a Double from STDIN and save it in R.
{       e# Filter; for each I in [0 ... R-1]:
  R\%!  e# Push the logical NOT of (R % I).
},      e# Keep the elements such that R % I == 0.
:D      e# Save the array of divisors in D.
:+R-g   e# Add the divisors, subtract R and compute the sign of the difference.
:Cz     e# Save the sign in C and apply absolute value.
"not "* e# Repeat the string "not " that many times.

" a perfect number, because "

D'+*    e# Join the divisors, separating by plus signs.
'=+D:++ e# Append a '=' and the sum of the divisors.
'=C+    e# Add the sign to '=', pushing '<', '=' or '>'.
_'=a&   e# Intersect a copy with ['='].
+a+     e# Concatenate, wrap in array and concatenate.
        e# This appends "<", "==" or ">".
R+      e# Append the input number.
S*      e# Join, separating by spaces.

2

Perl,148个字节

$a=<>;$_=join' + ',grep{$a%$_==0}1..$a-1;$s=eval;print"I am ".($s==$a?'':'not ')."a perfect number because $_ = $s ".(('==','>','<')[$s<=>$a])." $a"

带换行符:

$a=<>;
$_=join' + ',grep{$a%$_==0}1..$a-1;
$s=eval;
print"I am ".($s==$a?'':'not ')."a perfect number because $_ = $s ".(('==','>','<')[$s<=>$a])." $a"

我有过这样一捅,你可以绕过去除外括号节省10个字节'not ''==','>','<'报表,并从切换.,(因为没有当加入print荷兰国际集团的列表)。另外,在第一次使用分配任务时将其分配到parens中可以节省一些时间,如果您将逻辑略微更改为grep$a%_<1,1..($a=<>)-1,则$a!=($s=eval)&&'not '应该省掉一些!希望一切都有道理!
Dom Hastings

2

Lua,244 231字节

打高尔夫球:

n=io.read("*n")d={}s="1"t=1 for i=2,n-1 do if n%i==0 then table.insert(d,i)s=s.." + "..i t=t+i end end print(("I am%s a perfect number, because %s = %s"):format(t==n and""or" not", s, t..(t==n and" == "or(t>n and" > "or" < "))..n))

取消高尔夫:

n=io.read("*n")
divisors={}
sequence="1"
sum=1
for i=2,n-1 do
    if n%i==0 then 
        table.insert(divisors,i)
        sequence=sequence.." + "..i
        sum=sum+i
    end
end

print(("I am%s a perfect number, because %s = %s"):format(sum==n and""or" not", sequence, sum..(sum==n and" == "or(sum>n and" > "or" < "))..n))

2

JavaScript(ES6),146

使用模板字符串,它可以在Firefox和最新的Chrome浏览器中使用。

for(n=prompt(),o=t=i=1;++i<n;)n%i||(t+=i,o+=' + '+i)
alert(`I am ${t-n?'not ':''}a perfect number because ${o} = ${t} ${t<n?'<':t>n?'>':'=='} `+n)


2

红宝石,174 160 155 136 134 128 122个字节

n=6;a=[*1...n].reject{|t|n%t>0};b=a.inject(:+)<=>n;print"I am#{" not"*b.abs} a perfect number, because ",a*?+,"<=>"[b+1],n

保存了另外6个字节:)

感谢使用 Ruby打高尔夫球的技巧


打印命令仍然困扰着我。而且我需要找出一种缩短if语句三元组的方法?需要一个我无法提供的else子句,每个案例仅接受一个呼叫
Yuri Kazakov

只剩下一份印刷声明:)
Yuri Kazakov

1

C#,252个字节

class A{static void Main(string[]a){int i=int.Parse(a[0]);var j=Enumerable.Range(1,i-1).Where(o=>i%o==0);int k=j.Sum();Console.Write("I am "+(i!=k?"not ":"")+"a perfect number, because "+string.Join(" + ",j)+" = "+k+(k>i?" > ":k<i?" < ":" == ")+i);}}

1

Hassium,285字节

免责声明:由于命令行参数存在问题,仅适用于最新版本的Hassium。

func main(){n=Convert.toNumber(args[0]);s=1;l="1";foreach(x in range(2,n-3)){if(n%x==0){l+=" + "+x;s+=x;}}if(s==n)println("I am a perfect number, because "+l+" = "+s+" == "+s);else {print("I am not a perfect number, because "+l+" = "+s);if(s>n)println(" > "+n);else println(" < "+n);}}

更具可读性的版本:

func main() {
    n = Convert.toNumber(args[0]);
    s = 1;
    l = "1";
    foreach(x in range(2, n - 3)) {
            if (n % x== 0) {
                    l += " + " + x;
                    s += x;
            }
    }
    if (s == n)
            println("I am a perfect number, because " + l + " = " + s + " == " + s);
    else {
            print("I am not a perfect number, because " + l + " = " + s);
            if (s > n)
                    println(" > " + n);
            else
                    println(" < " + n);
    }

}


1
1.我似乎无法说服Hassium读取命令行参数。如果我执行mono src/Hassium/bin/Debug/Hassium.exe t.hs 6,它说System.ArgumentException: The file 6 does not exist.。2.此版本不适用于此版本该版本是发布此挑战之前的最新提交。请在您的回答中添加免责声明,表明您的提交没有竞争。
丹尼斯

我在Windows(使用MVS2015构建)上尝试了此操作,并得到了相同的错误。
Zereges

这个问题实际上是在15分钟前更新的。克隆Hassium,然后重新编译。非常抱歉,我遇到了同样的问题。
Jacob Misirian

1
它在最新版本中正常工作。现在,如果您可以添加免责声明,我将很乐意删除我的否决票。(顺便说一句,您可以通过添加@Dennis评论来对我进行回复。否则,我们不会收到您的回复。)
Dennis

@Dennis我添加了它。谢谢您的通知:)
Jacob Misirian

1

MATLAB 238

永远不会成为所有语言中最短的一种,但这是我对MATLAB的尝试:

n=input('');x=1:n-1;f=x(~rem(n,x));s=sum(f);a='not ';b=strjoin(strtrim(cellstr(num2str(f')))',' + ');if(s>n) c=' > ';elseif(s<n) c=' < ';else c=' == ';a='';end;disp(['I am ' a 'a perfect number, because ' b ' = ' num2str(s) c num2str(n)])

这是一种更具可读性的形式:

n=input();      %Read in the number using the input() function
x=1:n-1;        %All integers from 1 to n-1
f=x(~rem(n,x)); %Determine which of those numbers are divisors
s=sum(f);       %Sum all the divisors
a='not ';       %We start by assuming it is not perfect (to save some bytes)
b=strjoin(strtrim(cellstr(num2str(f')))',' + '); %Also convert the list of divisors into a string 
                                                 %where they are all separated by ' + ' signs.
%Next check if the number is >, < or == to the sum of its divisors
if(s>n)  
    c=' > ';    %If greater than, we add a ' > ' to the output string
elseif(s<n) 
    c=' < ';    %If less than, we add a ' < ' to the output string
else
    c=' == ';   %If equal, we add a ' == ' to the output string
    a='';       %If it is equal, then it is a perfect number, so clear the 'not' string
end

%Finally concatenate the output string and display the result
disp(['I am ' a 'a perfect number, because ' b ' = ' num2str(s) c num2str(n)])

我设法通过不使用函数来节省2个字节。而是运行代码行,并要求输入该数字作为输入。运行后,将在最后显示输出。


1

Perl 6、138字节

$_=get;
my$c=$_ <=>my$s=[+] my@d=grep $_%%*,^$_;
say "I am {
    'not 'x?$c
  }a perfect number, because {
    join ' + ',@d
  } = $s {
    «> == <»[1+$c]
  } $_"

(该计数将忽略换行和缩进,因为不需要它们)

@d是包含除数的数组。
$s持有除数之和。
$c是输入与除数之和之间比较的值。
(实际上$c是一个-101,但确实是一个Order::LessOrder::SameOrder::More

在中'not 'x?$c?$c在这种情况下,实际上abs $cx是相同,并且是字符串重复运算符。

«> == <»是的缩写( '>', '==', '<' )
由于$c具有之一-1,0,1,我们必须将其上移一个,才能使用它索引到列表中。

从技术上讲,这对于大于2 above的数字有效,但对于大于2⁶的数字则需要花费大量时间。


0

Pyth,84个字节

jd+,+"I am"*.aK._-QsJf!%QTtUQ" not""a perfect number, because"+.iJm\+tJ[\=sJ@"=<>"KQ

无效的答复,因为我拒绝执行=,并==在同一个方程式。


2
+1表示拒绝“在同一等式中实现=和==”。
theonlygusti 2015年

0

Ruby,164字节

->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}

测试

irb(main):185:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 6
I am a perfect number, because 1 + 2 + 3 = 6 == 6

irb(main):186:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 12
I am not a perfect number, because 1 + 2 + 3 + 4 + 6 = 16 > 12

irb(main):187:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 13
I am not a perfect number, because 1 = 1 < 13

0

Emacs Lisp,302字节

(defun p(n)(let((l(remove-if-not'(lambda(x)(=(% n x)0))(number-sequence 1(- n 1)))))(setf s(apply'+ l))(format"I am%s a perfect number, because %s%s = %s %s %s"(if(= s n)""" not")(car l)(apply#'concat(mapcar'(lambda(x)(concat" + "(number-to-string x)))(cdr l)))s(if(= sum n)"=="(if(> sum n)">""<"))n)))

非高尔夫版本:

(defun perfect (n)
  (let ((l (remove-if-not '(lambda (x) (= (% n x) 0))
              (number-sequence 1 (- n 1)))))
    (setf sum (apply '+ l))
    (format "I am%s a perfect number, because %s%s = %s %s %s" (if (= sum n)"" " not") (car l)
        (apply #'concat (mapcar '(lambda (x) (concat " + " (number-to-string x))) (cdr l)))
        sum (if(= sum n)
            "=="
          (if(> sum n)
              ">"
            "<"))
        n)))

0

Powershell,164字节

$a=$args[0]
$b=(1..($a-1)|?{!($a%$_)})-join" + "
$c=iex $b
$d=$a.compareto($c)
"I am $("not "*!!$d)a perfect number, because $b = $c $(("==","<",">")[$d]) $a"

一些常见但不太常见的PoSh技巧;

  • 创建总和,然后使用IEX进行评估
  • 比较以索引gt,lt,eq数组
  • !! $ d对于$ d = 1或-1将计算为true == 1,对于$ d = 0将为false == 0

0

150周

n=$0{for(p=i=s=n>1;++i<n;)for(;n%i<1;p+=i++)s=s" + "i;printf"I am%s a perfect number, because "s" = "p" %s "n RS,(k=p==n)?_:" not",k?"==":p<n?"<":">"}

浪费一些字节使输入正确无误1。我不确定这是否可以预期。

n=$0{
    for(p=i=s=n>1;++i<n;)
        for(;n%i<1;p+=i++)s=s" + "i;
    printf "I am%s a perfect number, because "s" = "p" %s "n RS,
           (k=p==n)?_:" not",k?"==":p<n?"<":">"
}

0

05AB1E,58 个字节

„I€ÜIѨ©OIÊi'€–}“€…íÀ‚³,ƒ«“®vy'+}\'=®ODI.S"==><"211S£sèIðý

在线尝试验证所有测试用例

说明:

Iۆ              # Push dictionary string "I am"
IѨ               # Push the divisors of the input-integer, with itself removed
   ©              # Store it in the register (without popping)
    O             # Get the sum of these divisors
     IÊi   }      # If it's not equal to the input-integer:
        '€–      '#  Push dictionary string "not"
“€…íÀ‚³,ƒ«“       # Push dictionary string "a perfect number, because"
®v   }            # Loop `y` over the divisors:
  y'+            '#  Push the divisor `y`, and the string "+" to the stack
      \           # Discard the final "+"
       '=        '# And push the string "="
®O                # Get the sum of the divisors again
  D               # Duplicate it
I.S               # Compare it to the input-integer (-1 if smaller; 0 if equal; 1 if larger)
   "==><"         # Push string "==><"
         211S£    # Split into parts of size [2,1,1]: ["==",">","<"]
              sè  # Index into it (where the -1 will wrap around to the last item)
I                 # Push the input-integer again
ðý                # Join everything on the stack by spaces
                  # (and output the result implicitly)

请参阅我的05AB1E技巧(如何使用字典?部分以了解为什么„I€Ü"I am"'€–"not"“€…íÀ‚³,ƒ«“"a perfect number, because"

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.