Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

factorial #40

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package org.eolang.benchmark;

class A {
class Factorial {
private int d;
A(int d) {
Factorial(int d) {
this.d = d;
}
public int get() {
return xget(this.d);
return Factorial.xget(this.d);
}
public static int xget(int xd) {
if (xd <= 0) {
return xd;
if (xd <= 1) {
return 1;
}
return xget(xd - 1);
return xget(xd - 1) * xd;
}
}

2 changes: 1 addition & 1 deletion src/main/java-synthetic/org/eolang/benchmark/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public static void main(String... args) {
long sum = 0L;
long start = System.currentTimeMillis();
for (long i = 0; i < total; ++i) {
sum += new A(42).get();
sum += new Factorial(42).get();
}
System.out.printf("sum=%d time=%d\n", sum, System.currentTimeMillis() - start);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@
*/
package org.eolang.benchmark;

class A {
class Factorial {
private int d;
A(int d) {
Factorial(int d) {
this.d = d;
}
public int get() {
if (d <= 0) {
return d;
if (d <= 1) {
return 1;
}
return new A(d - 1).get();
return new Factorial(d - 1).get() * d;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using a static method would be better here because creating an object with each recursive call fills up the stack, reducing efficiency.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@DIY0R this is the point of the optimization there -- to replace object with static method automatically

}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/eolang/benchmark/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static void main(String... args) {
long sum = 0L;
long start = System.currentTimeMillis();
for (long i = 0; i < total; ++i) {
sum += new A(42).get();
sum += new Factorial(42).get();
}
System.out.printf("sum=%d time=%d\n", sum, System.currentTimeMillis() - start);
}
Expand Down