I'm looking into an interesting interview question, and try to implement it with go.
(1) Input an integer number, say
i
(2) Calculate the summary of
1+2+...+i, output the summary
(3) Requirement: don't use multiply, don't use loop(
for/while), and don't useif/else
Well, in c++ or java this is pretty easy. We can use static variable to initialize an object array, while the objects's constructor function calculate this summary. Like this:
#include <iostream>
struct s {
static int count;
static int sum;
s() {++count; sum += count;}
};
int s::count = 0;
int s::sum = 0;
int main(int argc, char *argv[]) {
s obj[10];
std::cout << s::sum << std::endl; // 55, ok
return 0;
}
(2) in c++ we could also use template type deduction to do this. Plenty samples on the internet.
But, can we achieve this with go language?
I know that golang has neither constructor function, nor it supports static variable. And it doesn't have any template syntax. Plus, using recursive function still requires if branches in the code.
So is this possible to do same thing in go? (no for loop, no if else). Thanks.