codewars049: 可逆素數

Instructions

Emirpsjava

Solution

//--https://www.codewars.com/kata/55de8eabd9bef5205e0000ba/train/java
import java.util.*;
class Emirps{
    private static long reverse(long n){
        StringBuilder sb = new StringBuilder(String.valueOf(n));
        return Long.valueOf(sb.reverse().toString());
    }  
    private static Boolean isPrime(long n)  {
        long i;
        Boolean rslt = true;
        for(i = 2; i <= Math.sqrt(n); i++){
            if(n % i == 0){
                rslt = false;
                break;
            }    
        }    
        return rslt;
    }    
    
    public static long[] findEmirp(long n){
        if(n < 13){
            return new long[]{0,0,0};
        }    
        List<Long> list = new ArrayList<Long>();
        for(long i = 13; i < n; i++){
            if(Emirps.isPrime(i)){
                long t = Emirps.reverse(i);
                if(i != t && Emirps.isPrime(t)){
                    list.add(i);
                }                    
            }    
        }  
        long sum = 0;
        for(long x : list){
            sum += x;
        }    
        return new long[] {list.size(), list.get(list.size() - 1), sum};  
    }    
}

TDD

import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class EmirpsTest{
    @Test
    public void testSomething(){
        assertArrayEquals(new long[]{0,0,0}, Emirps.findEmirp(10));
        assertArrayEquals(new long[]{4,37,98}, Emirps.findEmirp(50));
        assertArrayEquals(new long[]{8,97,418}, Emirps.findEmirp(100));
    }    
}
相關文章
相關標籤/搜索