Skip to content

Instantly share code, notes, and snippets.

@A-pZ
Created July 24, 2018 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A-pZ/524a0e88b612bfde3b21bd1dc7b805da to your computer and use it in GitHub Desktop.
Save A-pZ/524a0e88b612bfde3b21bd1dc7b805da to your computer and use it in GitHub Desktop.
約数
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 約数。
*/
public class Divisor {
/**
* 引数に対する約数を返す。
* @param target 約数を出したい数値
* @return 約数のList表現。
*/
public static List<Integer> process(Integer target) {
if (target < 1) {
throw new IllegalArgumentException("引数が不正です");
}
Set<Integer> divisor = new HashSet<>();
Integer div = 1;
Integer upperLimit = target;
while(true) {
if (target % div == 0) {
divisor.add(div);
divisor.add(upperLimit);
upperLimit = target / div;
}
div++;
if ( div > upperLimit) {
break;
}
}
return divisor.stream().sorted().collect(Collectors.toList());
}
}
import spock.lang.Specification
import spock.lang.Unroll
@Unroll
class DivisorTest extends Specification {
def "process: 約数"() {
expect:
$expect == Divisor.process(target)
where:
target || $expect
1 || [1]
2 || [1,2]
4 || [1,2,4]
5 || [1,5]
8 || [1,2,4,8]
60 || [1,2,3,4,5,6,10,12,15,20,30,60]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment