Skip to content

Instantly share code, notes, and snippets.

@phaniram
Created January 26, 2012 11:47
Show Gist options
  • Save phaniram/1682408 to your computer and use it in GitHub Desktop.
Save phaniram/1682408 to your computer and use it in GitHub Desktop.
Interview Street Challenges - Lucky Numbers
package interviewstreet;
import java.util.Scanner;
public class lucky_num {
public static void main(String[] args) {
lucky_num sr = new lucky_num();
Scanner scanner = new Scanner(System.in);
int no_cases = scanner.nextInt();
for (int i = 0; i < no_cases; i++) {
System.out.println(sr.solve(scanner.nextLong(), scanner.nextLong()));
}
}
private int solve(long l, long m) {
int count = 0;
for (long i = l; i <= m; i++) {
if (logic(i)) {
count++;
}
}
return count;
}
private boolean logic(long i) {
return (isSUM(i) && isSUMsq(i));
}
private boolean isSUMsq(long i) {
int sum = 0;
while (i > 9) {
long k = i % 10;
i = i / 10;
sum += k * k;
}
sum += i * i;
return (isPrime(sum));
}
private boolean isSUM(long i) {
int sum = 0;
while (i > 9) {
long k = i % 10;
i = i / 10;
sum += k;
}
sum += i;
return (isPrime(sum));
}
private boolean isPrime(int num) {
if(num==2)
return true;
// check if n is a multiple of 2
if (num % 2 == 0 || num==1 )
return false;
// if not, then just check the odds
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0)
return false;
}
return true;
}
}
/**
*
* @author cypronmaya
*/
import java.util.Scanner;
class Solution {
boolean[] check;
public static void main(String[] args) {
Solution sr = new Solution();
sr.sieve(3358);
Scanner scanner = new Scanner(System.in);
int no_cases = scanner.nextInt();
for (int i = 0; i < no_cases; i++) {
System.out.println(sr.solve(scanner.nextLong(), scanner.nextLong()));
}
}
private int solve(long l, long m) {
int count = 0;
for (long i = l; i <= m; i++) {
if (logic(i)) {
count++;
}
}
return count;
}
private boolean logic(long i) {
return (isSUM_SUMsq(i));
}
private boolean isSUM_SUMsq(long i)
{
int sum = 0;
int sumsq=0;
while (i > 9) {
long k = i % 10;
i = i / 10;
sum += k;
sumsq += k * k;
}
sum += i;
sumsq +=i*i;
if(check[sum])
{
return check[sumsq];
}
return false;
}
private void sieve(int upto) {
int N = upto;
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
for (int i = 2; i * i <= N; i++) {
if (isPrime[i]) {
for (int j = i; i * j <= N; j++) {
isPrime[i * j] = false;
}
}
}
this.check = isPrime;
}
}
@saran87
Copy link

saran87 commented Mar 15, 2012 via email

@saran87
Copy link

saran87 commented Jun 8, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment