codewars065 - Backwards Read Primes

Instructions

https://www.codewars.com/kata/5539fecef69c483c5a000015/train/java

Solution:

public class BackWardsPrime {
	

	
	public static String backwardsPrime(long start, long end) {
		StringBuilder sb = new StringBuilder();
		
		for(long i = start; i <= end; i++){
			if(i % 2 == 0){
				continue;
			}
			long backwardRead = Long.valueOf(new StringBuilder(String.valueOf(i)).reverse().toString());
			if(isPrime(i) && !isPalindrome(i) && isPrime(backwardRead)){
				sb.append(String.valueOf(i)).append(" ");
			}
		}
		return sb.toString().trim();
	}
	
	private static boolean isPalindrome(long a){
		String str = String.valueOf(a);
		int len = str.length();
		for(int i = 0; i < len / 2; i++){
			if(str.charAt(i) != str.charAt(len - 1 - i)){
				return false;
			}
		}
		return true;
	}
	
	private static boolean isPrime(long a){
		if(a < 2){ // A prime number is no less than 2
			return false;
		}else{
			for(int i = 2; i <= Math.sqrt(a); i++){
				if(a % i == 0){
					return false;
				}
			}
		}
		
		return true;
	}

}

Sample Tests:

https://www.codewars.com/kata/5539fecef69c483c5a000015/train/java
相關文章
相關標籤/搜索