C,C ++,C#,D,Java,65 62字节
int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i>0?0:i;return s;}
由于相似性,这在所有这5种编程语言中均有效。
C,C ++和D优化:62 60字节
在C ++和D中,整数隐式转换为布尔值(零=> false,而不是零=> true),因此您不需要 !=0
int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i?0:i;return s;}
D优化:golfy模板系统,55字节
T d(T)(T n){T s,i=1;for(;i<=n;++i)s+=n%i?0:i;return s;}
测试代码:
C :
printf("%d %d %d %d %d", d(7), d(15), d(20), d(1), d(5));
C ++:
std::cout << d(7) << ' ' << d(15) << ' ' << d(20) << ' ' << d(1) << ' ' << d(5);
C# :
class FindSum
{
int d(int n) { int s = 0, i = 1; for (; i <= n; ++i) s += n % i > 0 ? 0 : i; return s; }
static void Main(string[] args)
{
var f = new FindSum();
Console.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}", f.d(7), f.d(15), f.d(20), f.d(1), f.d(5)));
}
}
D:
writeln(d(7));
writeln(d(15));
writeln(d(20));
writeln(d(1));
writeln(d(5));
Java的:
public class FindSum {
int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i>0?0:i;return s;}
public static void main(String[] args) {
FindSum f = new FindSum();
System.out.println(String.format("%d, %d, %d, %d, %d", f.d(7), f.d(15), f.d(20), f.d(1), f.d(5)));
}
}