Created
July 24, 2018 09:21
-
-
Save A-pZ/9c344ff7351c9f48eb5c521f7a8307db to your computer and use it in GitHub Desktop.
友愛数
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
import java.util.List; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
import lombok.Builder; | |
import lombok.Getter; | |
import lombok.ToString; | |
public class AmicableNumberLogic { | |
public List<AmicableNumbers> process(Integer start, Integer end) { | |
return IntStream.rangeClosed(start, end).boxed() | |
.map(i -> process(i)) | |
.filter(amic -> amic != null) | |
.peek(System.out :: println) | |
.collect(Collectors.toList()); | |
} | |
public AmicableNumbers process(Integer target) { | |
Integer primary = divisorSummary(target); | |
Integer secondary = divisorSummary(primary); | |
if (primary == null || secondary == null) { | |
return null; | |
} | |
if (primary.intValue() <= secondary.intValue()) { | |
return null; | |
} | |
if (target.intValue() == secondary.intValue()) { | |
return AmicableNumbers.builder().primary(primary).secondary(secondary).build(); | |
} | |
return null; | |
} | |
private Integer divisorSummary(Integer target) { | |
List<Integer> divisor = Divisor.process(target); | |
divisor.remove(divisor.size() -1); | |
if (divisor.isEmpty()) { | |
return null; | |
} | |
return divisor.stream().reduce((i1,i2) -> i1+i2).get(); | |
} | |
@Builder @Getter @ToString | |
public static class AmicableNumbers { | |
private Integer primary; | |
private Integer secondary; | |
} | |
} |
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
import spock.lang.Specification | |
import spock.lang.Unroll | |
@Unroll | |
class AmicableNumberLogicTest extends Specification { | |
AmicableNumberLogic sut = new AmicableNumberLogic() | |
def "友愛数_#primary"() { | |
when: | |
def expect = sut.process(primary) | |
then: | |
expect.primary == $primary | |
expect.secondary == $secondary | |
where: | |
primary || $primary | $secondary | |
220 || 284 | 220 | |
1184 || 1210 | 1184 | |
2620 || 2924 | 2620 | |
} | |
def "友愛数一覧"() { | |
when: | |
def expect = sut.process(2, 10000) | |
then: | |
expect | |
expect.get(0).primary == 284 | |
expect.get(0).secondary == 220 | |
expect.get(1).primary == 1210 | |
expect.get(1).secondary == 1184 | |
expect.get(2).primary == 2924 | |
expect.get(2).secondary == 2620 | |
expect.get(3).primary == 5564 | |
expect.get(3).secondary == 5020 | |
expect.get(4).primary == 6368 | |
expect.get(4).secondary == 6232 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment