Perfect Numbers Display Java - java

I have the following question for Homework
If a number is equal to the sum of all of its factors except itself, it is a perfect number. For example, 6 is a perfect number since 6 = 1 + 2 + 3.
Write a program that takes an input number and displays all perfect numbers up to and including that number.
and this is what I have so far
import java.util.*;
public class perfectnumbers
{
public static void main(String[] args){
Scanner console = new Scanner(System.in);
int externalNumber;
int internalNumber;
int internalTotal = 0;
System.out.println("Input Number");
externalNumber = console.nextInt();
while (externalNumber > 0) {
internalNumber = externalNumber;
while (internalNumber > 0) {
internalNumber = internalNumber - 1;
internalTotal = internalNumber + internalTotal;
}
if (internalTotal == externalNumber) {
System.out.println(internalTotal);
}
externalNumber = externalNumber - 1;
internalTotal = 0;
}
}
}
But for some Reason when ever I enter a number only 3 gets outputted... Can anyone help?

Perfect numbers (like other perfect things) are very scarce ones
https://oeis.org/A000396
they are (within the int range):
6, 28, 496, 8128, 33550336
(only three more 8589869056, 137438691328, 2305843008139952128 when working with long).
So you can implement it like that:
private static int[] perfectNumbers = new int[] {
6, 28, 496, 8128, 33550336
};
private static void displayPerfects(int upTo) {
for (int item : perfectNumbers)
if (item > upTo)
break;
else {
System.out.print(item);
System.out.println();
}
}
...
public static void main(String[] args) {
...
System.out.println("Input Number");
...
externalNumber = console.nextInt();
...
displayPerfects(externalNumber);
}
Please note, that efficiency really matters in your case, e.g. how much time does it take if your're given, say, 2000000000? All you have to do is to test at most five values.

You never check for a factor. Do something like this:
while (externalNumber > 0) {
internalNumber = externalNumber-1; //Make sure to subtract one here
while (internalNumber > 1) { //Change this to 1 so you don't divide by 0
internalNumber = internalNumber - 1;
if (externalNumber%internalNumber==0){ //Check for factor
internalTotal = internalNumber + internalTotal;
}
}
if (internalTotal == externalNumber) {
System.out.println(internalTotal);
}
externalNumber = externalNumber - 1;
internalTotal = 0;
}

Related

Finding Twin Primes with Constructor

Just for fun, i wanted to see whether i could employ a code to display twin primes as practice for learning Constructors. I though i had used a good logic but for some reason i couldnt make it work.
This program is to print all twin primes(primes with 1 gap between them) till a given number as input by the user.
package X;
import java.io.*;
import java.util.*;
class TwinPrimeWithConstructor {
int limit;
public void Twin() {
limit = 0;
}
public static void input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Limit");
int limit = input.nextInt();
}
public void display() {
for (int k = 1; k <= (limit - 2); k++) {
int a = prime(k);
int b = prime(k + 2);
if (a == 1 && b == 1) {
System.out.println(k + "," + k + 2);
}
}
}
public int prime(int n) {
int c = 0;
int d = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
c = c + 1;
}
}
if (c == 2) {
d = 1;
return d;
} else {
return d;
}
}
void main() {
TwinPrimeWithConstructor ob = new TwinPrimeWithConstructor();
ob.input();
ob.display();
}
}
This program manages to correctly detect primes and asks for input,but does not give any output. Can someone make it clear to me? I'm still learning java so any help would be appreciated.
Also since im new, if you find any bad habits in my code, please feel free to tell me so i can become a better programmer.
You are not getting any output because this.limit is always 0:
int limit = Input.nextInt();
You should assign the input to your instance field rather than to a new local variable. To do this, the input method must not be static:
public void input() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Limit");
limit = input.nextInt();
}

My code is giving a wrong answer in codechef

My code works fine in my compiler and I even tried another few online compilers but still not able to find the issue, can someone help!
Question
https://www.codechef.com/JUNE18B/problems/NAICHEF
Once, after a stressful day, Chef decided to relax and visit a casino near his house to gamble. He feels lucky and he's going to bet almost all of his money.
The game Chef is going to play in the casino consists of tossing a die with N
faces twice. There is a number written on each face of the die (these numbers are not necessarily distinct). In order to win, Chef must get the number A
on the first toss and the number B
on the second toss of the die.
The excited viewers want to know the probability that Chef will win the game. Can you help them find that number? Assume that Chef gets each face of the die with the same probability on each toss and that tosses are mutually independent.
My submission
import static java.lang.System.exit;
import java.util.*;
import java.lang.*;
/**
*
* #author williamscott
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean status = true;
int T = Integer.parseInt(in.nextLine());
//Original Constraint
if (T < 1 || T > 10) {
// System.out.println("Please follow original constraint for T");
// exit(0);
status = false;
}
int N[] = new int[T], A[] = new int[T], B[] = new int[T];
float Probability[] = new float[T];
for (int t = 0; t < T; t++) {
String[] input = in.nextLine().split(" ");
N[t] = Integer.parseInt(input[0]);
A[t] = Integer.parseInt(input[1]);
B[t] = Integer.parseInt(input[2]);
if (N[t] < 1 || N[t] > 100) {
// System.out.println("Please follow original constraint for N");
// exit(0);
status = false;
}
if (A[t] < 1 || A[t] > N[t]) {
// System.out.println("Please follow original constraint for A");
// exit(0);
status = false;
}
if (B[t] < 1 || B[t] > N[t]) {
// System.out.println("Please follow original constraint for B");
// exit(0);
status = false;
}
float pn, pa = 0, pb = 0;
String[] f = in.nextLine().split(" ");
pn = f.length;
if (pn != N[t]) {
// System.out.println("Inputs Invalid");
// exit(0);
status = false;
}
for (String f1 : f) {
if (Integer.parseInt(f1) < 1 || Integer.parseInt(f1) > N[t]) {
// System.out.println("Please follow original constraint for x (input)");
// exit(0);
status = false;
}
if (Integer.parseInt(f1) == A[0]) {
pa++;
}
if (Integer.parseInt(f1) == B[0]) {
pb++;
}
}
Probability[t] = (pa / pn) * (pb / pn);
}
if (status) {
for (float d : Probability) {
System.out.println(String.format("%.10f", d));
}
}
}
}
Error:
First of all, you should use double rather then float (precision matters)!
Secondly, you should update your conditions for status because you take in consideration only the first sub-task with (T less than 10, and N less than 100) which will give you only 20 points! the second sub-task (that rewards 80 points) takes a T less than 70 and a N less than 1000.
Finally, the issue with the code comes from the condition of updating pa & pb, you use :
Integer.parseInt(f1) == A[0] // same for B[0]
instead of
Integer.parseInt(f1) == A[t] // same for B[t]
Here is the complete code and submission results
import java.util.*;
import java.lang.*;
/**
*
* #author aoubidar
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// number of test cases
int T = Integer.parseInt(in.nextLine());
int[] N = new int[T];
int[] A = new int[T];
int[] B = new int[T];
double[] Probability = new double[T];
for (int t = 0; t < T; t++) {
String[] input = in.nextLine().split(" ");
N[t] = Integer.parseInt(input[0]);
A[t] = Integer.parseInt(input[1]);
B[t] = Integer.parseInt(input[2]);
int total, pa = 0, pb = 0 ;
String[] faces = in.nextLine().split(" ");
total = faces.length;
for (String f : faces) {
if (Integer.parseInt(f) == A[t]) {
pa++;
}
if (Integer.parseInt(f) == B[t]) {
pb++;
}
}
double pn = (double) (total * total);
Probability[t] = (pa * pb) / pn ;
}
for (double d : Probability) {
System.out.println(d);
}
}
}
submission success:
Never compare floating point numbers using == or !=. Digital computers cannot represent floating point numbers with absolute precision, and so these tests will often fail.
Never use float when double will work. You gain little by using float and lose a much precision.
Leave your integer input as ints, and convert to double only when needed, here cast to double when doing probability calculations
Don't over-complicate your code as you're doing, and use testable methods to help simplify as well. No need to use arrays for example. The constraints mentioned above likely do not need to be tested in your program but rather assumed to be true.
Use variable names that comply with Java naming standards, and that make sense.
For example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// get number of trys
String line = scanner.nextLine();
int trys = Integer.parseInt(line.trim());
for (int i = 0; i < trys; i++) {
// for each try, calc probability
double probability = processTry(scanner);
System.out.println(probability);
}
scanner.close();
}
private static double processTry(Scanner scanner) {
String line;
// get first line
line = scanner.nextLine();
// use Scanner to get ints from line
Scanner lineScan = new Scanner(line);
//number of faces
int numberOfFaces = lineScan.nextInt();
int a = lineScan.nextInt();
int b = lineScan.nextInt();
lineScan.close();
// scanner to get face values
line = scanner.nextLine();
lineScan = new Scanner(line);
// count of how many faces match a and b values
int aMatch = 0;
int bMatch = 0;
for (int i = 0; i < numberOfFaces; i++) {
int face = lineScan.nextInt();
if (a == face) {
aMatch++;
}
if (b == face) {
bMatch++;
}
}
lineScan.close();
// only cast to double when need for calc
double probability = ((double) (aMatch * bMatch) / (numberOfFaces * numberOfFaces));
return probability;
}
}
Let's suppose there is n(A) is the number of occurrence of A on the dice and n(B) is the number of occurrence of B on the dice. In this, the probability that A will be thrown at a given time is
P(A) = n(A) / N
and the probability that B will be thrown at a given time is
P(B) = n(B) / N
The probability that A will be thrown first and B will be thrown second is
P(A) ^ P(B) = P(A) * P(B)
since the experiments are independent.
P(A) * P(B) = n(A) * n(B) / N^2
since this is precisely in your code, you have implemented a correct algorithm for the calculation, so the problem must consist in something else than the algorithm.
Usage of float
The usage of float might be causing slight differences between your result and the expected result. Change it to double.

How to determine why a Java program is not accepting 7 console inputs?

I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}

Java input array based on if/else using recursion only

I've been given the following homework...
We have bunnies standing in a line, numbered 1, 2, ... n
The even numbered bunnies (2, 4, ..) have the normal 2 ears.
The odd numbered bunnies (1, 3, ..) have 3 ears.
Recursively return the number of "ears" in the bunny line 1, 2, ... n (without loops or multiplication).
I tried first with loops:
import java.util.Scanner;
public class BunnyEars {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int a = in.nextInt();
int [] bunnies = new int [a];
//for loop(non-recursive method)
for(int i=0;i<bunnies.length;i++)
{
if(i%2==0)
{
bunnies[i]=2;
}
else
{
bunnies[i]=3;
}
System.out.println("Bunny ["+i+"] : "+bunnies[i]+" ears");
}
}
}
However, after removing the loop, I'm not sure how to increment the array number as shown here:
import java.util.Scanner;
public class BunnyEars {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int a = in.nextInt();
int [] bunnies = new int [a];
Ears(bunnies);
// TODO Auto-generated method stub
}
public static void Ears(int [] bunnies) {
int x =0;
bunnies[x]=bunnies[x+1];
if(x<bunnies.length)
{
if(x%2==0)
{
bunnies[x]=2;
}
else
{
bunnies[x]=3;
}
}
System.out.println("Bunny ["+x+"] : "+bunnies[x]+" ears");
}
}
I will keep getting just "bunny[0]: 2 ears". There is another bunny question on stackoverflow but the output desired is different. Been searching around but can't seem to find a similar question. Any ideas?
I'd go with the pseudocode below. I don't want to write real code because it's a homework assignment and you're supposed to learn from trial and error.
So here is the pseudocode. You'll have to figure out how to end the recursion.
int ears(int[] bunnies) {
return Ears(bunnies, 0);
}
int ears(int[] bunnies, int index) {
int ears = countEars(bunnies, index);
return ears + ears(bunnies, index + 1);
}
public class BunnyEars {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int a = in.nextInt();
printEar(a - 1);
}
public static void printEar(int i) {
if (i > 0) {
printEar(i - 1);
}
System.out.println("Bunny [" + i + "] : " + ((i % 2 == 0) ? 2 : 3) + " ears");
}
}

Finding the largest, second largest, second smallest, and smallest int from an array in java

I'm using a method to print the largest, second largest, smallest, and second smallest integers. This is what I have so far for the base:
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
This is the method being called so far:
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
The actual output is to formatted like
(largest,secondlargest),(smallest,secondsmallest)
I've never used an array before, and I'm not sure how to use loops with it to find the values. How do I begin this?
Here is the complete code for my program. You can disregard the second and third case, however, I still need help with the third. I need to display all prime numbers in order. Here is the requirement: Twin Prime Numbers: This should let the user specify a limit n (I used limit instead) (if n is 1000, then consider 1
to 1000), and lists the pairs of twin primes up to n. The sample run is (3,5),(5,7),(11,13),(17,19)
The complete code:
import java.util.Scanner;
public class PatternChecker{
// The scanner is accessible for every method included
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// Variables
int limit;
System.out.println("List of Pattern Checker problems:\n1) Largest and Smallest Pairs\n2) Patterns of Triangles\n3) Twin Prime Pairs\n4) Quit");
System.out.print("Choice: ");
int choice = input.nextInt();
// The switch statement for the variable "choice" and each case
switch (choice) {
default:
System.out.println("\n*** INVALID OPTION");
break;
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
case 2:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(triangleOne(limit));
System.out.println(triangleTwo(limit));
System.out.println(triangleThree(limit));
System.out.println(triangleFour(limit));
break;
case 3:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(primePairs(limit));
break;
case 4:
System.out.println("\n*** End");
break;
}
}
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle One)
public static String triangleOne(int limit) {
System.out.println("*** Patterns of Triangles");
for (int x = 1; x <= limit; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Two)
public static String triangleTwo(int limit) {
for (int x = limit; x > 0; x--) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Three)
public static String triangleThree(int limit) {
for (int row = 1; row <= limit; row++) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = row; num > 0; num--) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Four)
public static String triangleFour(int limit) {
for (int row = limit; row >= 0; row--) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = 1; num <= row; num++) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 3 Method: Twin Prime Pairs
public static String primePairs(int limit) {
System.out.println("*** Twin Prime Numbers up to " + limit);
return "";
}
}
Ok based on the comment i have written a quick answer with arraylists. hope this helps.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MaxMin {
private List<Integer> alist = new ArrayList<Integer>();
public static void main(String args[]) {
MaxMin maxmin = new MaxMin();
maxmin.init();
}
public void init() {
System.out.println("Welcome!!!");
readFromUser();
printUserList();
doSort();
display();
}
public void readFromUser() {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print("Enter the total number of elements :");
Integer totalElements = scanner.nextInt();
for (int i=0;i<totalElements;i++) {
System.out.print("Enter the " + i +" number");
alist.add(scanner.nextInt());
}
}catch(Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
public void printUserList() {
System.out.println("user entered list is :");
System.out.println(alist);
}
public void doSort() {
Collections.sort(alist);
}
public void display() {
System.out.println("(" +alist.get(alist.size()-1)+ "," +alist.get(alist.size()-2)+ ")" + "(" +alist.get(0)+"," +alist.get(1) +")");
}
}
I hope this isn't a homework problem, but the idea is to use a loop with the array, and keep track of the largest and smallest numbers.
Start with assigning the smallest number variable to Integer.MAX_VALUE, so the first number you check will be assigned to the smallest number, because all integer values except 2^31 - 1 are smaller than Integer.MAX_VALUE, and you do that for biggest too, but with Integer.MIN_VALUE.
And then whenever you assign the biggest number again, you assign the secondBiggest variable to the "biggest" variable.
With that in mind, you just need to loop through the values of the array and check if they're larger than the biggest (in which you re-assign it) or smaller than the smallest(same thing as biggest).
int[] array = new int[]{5, 3, 4, 1, 2};
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
^
Example of looping through an array
I created an example for you.
First of all it generates a list of prime numbers till the limit (in this case hardcoded 100). Next it asks for all prime pairs and prints them. The pairs are stored in an ArrayList so it is very easy to get the first and the last pair.
It's not realy hard to understand so I don't know what to explain. Take a look at the code and if you have any questions feel free to ask.
import java.util.ArrayList;
public class PatternChecker {
public ArrayList<Integer> primes = new ArrayList<>();
public static void main(String[] args) {
PatternChecker pc = new PatternChecker();
pc.detectPrimes(100);
ArrayList<int[]> numbers = pc.getPairs();
System.out.println("Print all pairs: ");
numbers.stream().forEach((intA)->System.out.println(intA[0]+" / "+intA[1]));
System.out.println("Print just the greatest and the smallest pair: ");
System.out.println("("+numbers.get(0)[0]+","+numbers.get(0)[1]+")");
System.out.println("("+numbers.get(numbers.size()-1)[0]+","+numbers.get(numbers.size()-1)[1]+")");
}
public void detectPrimes(int limit) {
for(int i=2;i<limit;i++)
if(isPrime(i))
primes.add(i);
}
protected boolean isPrime(int no) {
for(int i=0;i<primes.size();i++)
if(no % primes.get(i) == 0) return false;
return true;
}
public ArrayList<int[]> getPairs() {
ArrayList<int[]> result = new ArrayList<>();
int last = primes.get(0);
for(int i=1;i<primes.size();i++) {
if(primes.get(i)==last+2) {
int[] resH = new int[2];
resH[0] = last;
resH[1] = primes.get(i);
result.add(resH);
}
last = primes.get(i);
}
return result;
}
}

Categories