Created
April 29, 2011 03:48
-
-
Save berlinbrown/947800 to your computer and use it in GitHub Desktop.
Scalar Summation in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple scalar sum class. | |
*/ | |
package org.berlin.algo.basic; | |
/** | |
* Simple scalar sum class. | |
* Normally use j=1, stops at n. | |
* <pre> | |
* Sum: | |
* i=1, n=100, summation = 5050 | |
* </pre> | |
* | |
* <pre> | |
* System.out.println("Sum: " + new ScalarSum().sum(new ScalarSum.Fx(), 1, 100)); | |
* Output: 5050 | |
* </pre> | |
*/ | |
public class ScalarSum { | |
public int sum(final f f, int j, int n) { | |
int sum = 0; | |
for (int index = j; index <= n; index++) { | |
sum = sum + f.$(index); | |
} | |
return sum; | |
} | |
public interface f { | |
public int $(final int x); | |
} | |
public static class Fx implements f { | |
public int $(int x) { | |
return x; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment