I was asked to write code for the following Question,
Find the prime numbers in an array of given numbers and print the sum
of squares of the prime numbers found.
And this was my code:
import java.util.*;
public class primenumber2
{
public static void main(String[] args)
{
int[] int1 = {2,3,4,6,11,13,17,99};
int square=0;
int result=0;
boolean isprime = true;
for(int i=0;i<int1.length;i++)
{
int temp=int1[i];
for(int j=1;j<i;j++)
{
if(temp%j==0)
{
isprime = false;
}
else
isprime = true;
}
if(isprime)
{
System.out.println(temp);
square = temp*temp;
result = result+square;
}
}
System.out.println(result);
}
}
Now the problem is that every number that ends with 9,gets added as a prime,i couldn't find out why.
Can someone help me with this? and also if ,possible a better way to solve this problem just using the basic functions and classes.
2 problems
you start for-loop from 1
your check until j<i which is the index of the first loop.
for(int j=1;j<i;j++)
// ↑ why limit this loop at index of the outer loop?
// ↑ start at 1 (WRONG!)
To check primes, you must start with number % 2 until number % number - 1
for(int j=2;j<temp;j++)
But in order to clarify and save iterations, I would make a method to check primes like this:
private static boolean isPrime(int toCheck) {
for (int i = 2; i < toCheck; i++) {
// stop iterating if you know number is even
if (toCheck % i == 0) return false;
}
return true;
}
Then you can use it like:
public static void main(String[] args) throws Exception {
int[] int1 = { 2, 3, 4, 6, 11, 13, 17, 99 };
int square = 0;
int result = 0;
for (int i = 0; i < int1.length; i++) {
if (isPrime(int1[i])) {
System.out.println(int1[i]);
square = int1[i] * int1[i];
result += square;
}
}
System.out.println(result);
}
OUTPUT:
2
3
11
13
17
592
which seems correct
Related
The 7th number displayed separate. So in my opinion I can't put the 7 numbers in one array.
I want to print the 1st 6 in a line and the 7th number separate.
Can someone help?
The first 6 numbers are between 1 - 49 and sorted low-high and do not contain a duplicate.
The 7th number is no one of the first 6 but between 1 - 49 too.
I already generate a 7th number but sometimes it is a duplicate from one of the first 6.
This is the task :
Write a program that generates random numbers that I can enter on my next lottery ticket. When the program is started, it should generate 7 numbers. The first 6 are to be output in ascending order. The 7th number is the super number. It is issued separately. It is not sorted with .
import java.util.Arrays;
import java.util.Random;
public class RandomizedArrayExample
{
public static int[] zahlen = null;
public static void main(String[] args)
{
Random W = new Random();
try
{
zahlen = new int[6];
Random y = new Random();
int gesamt = 0;
boolean status = true;
while(status)
{
int zahl = y.nextInt(49)+1;
if(!isCompleted()){
if(!isDuplicate(zahl)){
zahlen[gesamt] = zahl;
gesamt++;
}else{
continue;
}
}else{
status = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
for(int q = 0; q<6-1; q++) {
for (int j = q+1; j<zahlen.length; j++) {
if(zahlen[q] > zahlen[j]) {
int k = zahlen[q];
zahlen[q] = zahlen[j];
zahlen[j] = k;
}
}
}
String ihreZahlen = "----Ersten 6 Zahlen----";
String superZahl = "-------Superzahl-------";
int x = W.nextInt(49)+1;
System.out.println(ihreZahlen);
System.out.println(Arrays.toString(zahlen));
System.out.println(superZahl);
}
public static boolean isCompleted(){
boolean status = true;
for (int i = 0; i < zahlen.length; i++){
if(zahlen[i]==0){
status = false;
break;
}
}
return status;
}
public static boolean isDuplicate(int num){
boolean status = false;
for (int i = 0; i < zahlen.length; i++){
if(zahlen[i]== num){
status = true;
break;
}
}
return status;
}
}
This is a sample output:
----Ersten 6 Zahlen----
[14, 16, 30, 38, 41, 45]
-------Superzahl-------
38
You see the 38 is a duplicate
When you do int x = W.nextInt(49)+1; you risk getting a duplicate as in your example output. Instead you need a loop where you again use isDuplicate() to check whether you got a duplicate and break out of the loop when you haven’t.
For a different and maybe batter solution there is nothing wrong with putting all 7 numbers in one array. You can always take them out from there into 6 numbers and 1 number. Here’s one way:
Random w = new Random();
int[] allNumbers = IntStream.generate(() -> w.nextInt(49) + 1)
.distinct()
.limit(7)
.toArray();
int[] numbers = Arrays.copyOf(allNumbers, 6);
Arrays.sort(numbers);
int superNumber = allNumbers[6];
String ihreZahlen = "----Ersten 6 Zahlen----";
String superZahl = "-------Superzahl-------";
System.out.println(ihreZahlen);
System.out.println(Arrays.toString(numbers));
System.out.println(superZahl);
System.out.println(superNumber);
Example output:
----Ersten 6 Zahlen----
[6, 8, 12, 16, 35, 42]
-------Superzahl-------
33
Here you assign x a value without checking if it's a duplicate:
int x = W.nextInt(49)+1;
add some logic to check if it is not already in your "zahlen array". The easiest way would be to add a while loop beneath it and use your isDuplicate method to check if it is already in your zahlen array. As long as this is the case you assign x new values.
int x;
do{
x = W.nextInt(49)+1;
}while(isDuplicate(x));
Ok so I been working on this assignment all day for the past 3 days but I haven't had any luck. I wasn't going to ask for help but I finally gave up. But there is also one more thing I need to implement to the code. This is what I gotta implement "Find the length of the longest continuous series of positive numbers in the array data. If the contents were: 4 5 0 2 . . . -1 88 78 66 -6. The length would be 3. For this problem, 0 is considered non-negative but not positive". Plus I have an issue where I can't print the largest int in the array of 20.
import java.util.Random;
import java.util.ArrayList;
public class arrayops {
public static int findLargest(ArrayList<Integer> nums) {
int greatestnum = nums.get(0);
for (Integer item : nums) {
if (item > greatestnum) {
greatestnum = item;
}
}
return greatestnum;
}
public static int randomData(ArrayList<Integer> nums) {
int[] array = new int [20];
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = -100 + random.nextInt(201);
}
return -100 + random.nextInt(201);
}
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(1);
nums.add(4);
nums.add(13);
nums.add(43);
nums.add(-25);
nums.add(17);
nums.add(22);
nums.add(-37);
nums.add(29);
System.out.println("The Greatest Number from the hardcoded numbers " + findLargest(nums));
System.out.println("The Greatest number from the random numbers " + randomData(nums));
}
}
The findLargest method:
public static int findLargest(ArrayList<Integer> nums) {
int greatestnum = 0;
int greatestLen = 0;
for (Integer item : nums) {
if (item > 0) {
greatestLen++ ;
if(greatestLen > greatestnum)
greatestnum = greatestLen;
}
else
greatestLen = 0;
}
return greatestnum;
}
Logic used:
Keep the length of the longest chain encountered, and the length of current chain, in two separate variables (greatestnum and greatestLen respectively)
Increment greatestLen every time a positive number is encountered. If the number if less than or equal to zero, reset this count.
If the length of current chain is greater than the previous longest chain, sent the longest chain size to current chain size.
The problem is you created a list with random numbers but never put that list into the findLargest method. You also never created a method to find the consecutive positive numbers. If you didn't know how to go about coding it, I recommend drawing out an algorithm on paper.
Largest value in ArrayList...
public static int findL(ArrayList<Integer> nums)
{
int top = nums.get(0);
for(int i = 0; i<nums.size(); i++)
{
if(nums.get(i)>top)
{
top = nums.get(i);
}
}
return top;
}
Largest number of consecutive positives...
public static int positiveString(ArrayList<Integer> nums)
{
int longest = 0;
int count = 0;
for(int i = 0; i<nums.size(); i++)
{
if(nums.get(i) > 0)
{
count++;
}
else
{
if(longest<count)
{
longest = count;
}
count = 0;
}
}
return longest;
}
If you want to arrange the numbers into order you can simply use java.util.TreeSet. Then use the method last() to get the largest number.
public static int findLargest(ArrayList<Integer> nums) {
return new TreeSet<Integer>(nums).last();
}
I've been working on this code for class that needs to find the users desired number of palindromic prime numbers. Everything works fine when I have the while(primeCounter < desiredNumPrimes) except that it outputs one less than the desired number of prime numbers. I attempt to correct this by having the while statement be "<=" instead, but then I get an Array Index Out Of Bounds Exception. As you can see, I even check to make sure that the index of the array is not less that the index I am attempting to use in the if statement
Any help is appreciated.
import java.util.Scanner;
public class PalPrimes
{
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
int primeCounter=1, numberToCheck=2; //start checking at 2 because primes >1
System.out.println("Please enter the desired number of palindromic primes");
int desiredNumPrimes = scan.nextInt();
int[] palPrimes = new int[desiredNumPrimes-1];
System.out.print(palPrimes.length);
//find palindromic primes
while(primeCounter<desiredNumPrimes){
if(isPrime(numberToCheck)==true && isPalindrome(numberToCheck)==true){
palPrimes[primeCounter-1]= numberToCheck;
numberToCheck++;
primeCounter++;
}
else{
numberToCheck++;
}
}
//display palindromic primes
if(primeCounter==desiredNumPrimes){
for(int i = 0; i<palPrimes.length; i++){
if(i%10==0){
System.out.println();
}
System.out.print(palPrimes[i] + " ");
}
}
}
//Check if number is a prime
public static boolean isPrime(int num){
if(num == 2){
return true;
}
for( int divisor = 2; divisor <= num/2; divisor++){
if (num % divisor ==0){
return false;
}
}
return true;
}
//reverse number to begin testing if palindrome
public static int reverse(int num){
int testNum = 0;
while(num !=0){
int lastDigit = num%10;
testNum = testNum*10+lastDigit;
num = num/10;
}
return testNum;
}
//Check if number is a palindrome
public static boolean isPalindrome( int num){
return num == reverse(num);
}
}
The issues are with initializations. The below 3 changes will resolve the issue. You are getting arrayindexoutofbounds since you are trying to change only the initialization but not the assignment
int primeCounter with 0
int[] palPrimes = new int[desiredNumPrimes];
palPrimes[primeCounter]= numberToCheck;
Start the prime counter at 0 as you haven't found any primes yet.
int primeCounter=0, numberToCheck=2;
You're making the size of palPrimes 1 less than the desired number of primes, so it will never be able to contain the desired number of primes. Instead, make it
int[] palPrimes = new int[desiredNumPrimes];
Then, you check for palPrimes[primeCounter-1] = numberToCheck;
Seeing as we started the counter at 0, this should be changed to:
palPrimes[primeCounter] = numberToCheck;
And the program should work.
Set up to print out all false values which are prime numbers however out of 25 it prints. 3, 5, 7, 8, 9, 11, 13, 14, 15, 17, 19, 20, 21, 23, 24, not sure why some of them slip by. Any insight into the matter would be nice.
Or simply pointing me in the write direction.
Why are the non-prime numbers such as 8 being printed?
import java.util.Arrays;
import java.util.Scanner;
class Sieve {
public static void main(String args[]) {
Scanner inputScanner;
inputScanner = new Scanner(System.in);
//determine max value
System.out.println("I will determine all the primality of a set of numbers, enter the max");
int n = Integer.parseInt (inputScanner.nextLine());
boolean[] truedBooleanArray = calcBooleanMax (n);
//call upon function to check primality
boolean [] primeNumbers = calcPrimality (truedBooleanArray);
// call upon function to print out prime numbers
printPrimes(primeNumbers);
}
public static boolean[] calcBooleanMax(int maxNumber) {
boolean [] maxNumberArray = new boolean [maxNumber];
maxNumberArray[0] = false;
maxNumberArray[1] = false;
//asigns 1, 0 to false
//change all boleans within array from false to true!
for(int i=1; i < maxNumber; i++) {
maxNumberArray [i] = true;
}
return maxNumberArray;
}
public static boolean[] calcPrimality(boolean [] truedBooleans) {
for(int i = 2; i <=truedBooleans.length; i++) {
//check every number greater than 1 for primality.
if (truedBooleans[i-1]) {
}
//finds multiples and makes sure they arent stored
for(int j = 2*i; j <= truedBooleans.length; j+= i) {
truedBooleans[j-1] = false;
}
}
return truedBooleans;
}
public static void printPrimes(boolean [] thePrimeNumbers){
System.out.println("The prime numbers are [");
for(int i = 2; i<thePrimeNumbers.length; i++) {
if(thePrimeNumbers[i] == false ) {
System.out.print(i + ", ");
}
}
}
}
You have a few errors.
The array must be one larger than the given max
You are accidentally adding one back to the sieve when initializing
When removing multiples from the sieve, you must first make sure the initial number "i" is still in the sieve
You want to print the items that are still in the sieve, so print when true rather than false
Here is the fixed code
public static boolean[] calcBooleanMax(int maxNumber) {
boolean [] maxNumberArray = new boolean [maxNumber+1];
maxNumberArray[0] = false;
maxNumberArray[1] = false;
//asigns 1, 0 to false
//change all boleans within array from false to true!
for(int i=2;i < maxNumber+1; i++) {
maxNumberArray [i] = true;
}
return maxNumberArray;
}
public static boolean[] calcPrimality(boolean [] truedBooleans){
for(int i = 2; i <truedBooleans.length; i++) {
if(truedBooleans[i]) {
//finds multiples and makes sure they arent stored
for(int j = 2*i; j < truedBooleans.length; j+= i) {
truedBooleans[j] = false;
}
}
}
return truedBooleans;
}
public static void printPrimes(boolean [] thePrimeNumbers){
System.out.println("The prime numbers are [");
for(int i = 2;i<thePrimeNumbers.length;i++) {
if(thePrimeNumbers[i] ) {
System.out.print(i + ", ");
}
}
}
A simpler solution is a less literal interpretation of the algorithm. Rather than keeping a literal list of booleans, you can keep a list of the current primes. This makes the code simpler and easier to read.
Here is an example of a solution (that relies on Java 8 streams):
class Sieve {
private long current = 2;
private final List<Long> primes = new ArrayList<>();
public long nextPrime() {
while (primes.stream().anyMatch(p -> current % p == 0))
current++;
primes.add(current);
return current;
}
}
I'm having a difficult time with my program! For this method I have to check to see if all the numbers are distinct and I can't figure out for the life of me what I am doing wrong. I don't know if using an array is the best way to go. I must call the getDigit method.
for (int i = 0; i <= numDigits(number); i++) {
int digit = getDigit(number,i);
if (digit == getDigit(number,i)) {
return false;
}
}
return true;
You can first get each digit from the number and add them to a HashSet, then compare the size of HashSet with the number of digits present in the number
You can try this code:
public static void main(String[] args) {
int val = 123554;
Set<Integer> set = new HashSet<Integer>(); // HashSet contains only unique elements
int count = 0; // keeps track of number of digits encountered in the number
// code to get each digit from the number
while (val > 0) {
int tempVal = val % 10;
set.add(tempVal); // add each digit to the hash set
// you can have a boolean check like if(!set.add(tempVal)) return false; because add() returns false if the element is already present in the set.
val = val / 10;
count++;
}
if (count == set.size()) {
System.out.println("duplicate digit not present");
} else {
System.out.println("duplicate digit present");
}
}
Splitting Int into single digits:
Use something similar to this:
Code to print the numbers in the correct order:
int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
stack.push( number % 10 );
number = number / 10;
}
while (!stack.isEmpty()) {
print(stack.pop());
}
Source
Checking for Duplicates:
Again, something similar to this:
public static boolean duplicates (int [] x, int numElementsInX ) {
Set<Integer> set = new HashSet<Integer>();
for ( int i = 0; i < numElementsInX; ++i ) {
if ( set.contains( x[i])) {
return true;
}
else {
set.add(x[i]);
}
}
return false;
}
Source
Alternative
If you can split the array, an alternative could be to use:
int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 };
Arrays.sort(numbers);
for(int i = 1; i < numbers.length; i++) {
if(numbers[i] == numbers[i - 1]) {
System.out.println("Duplicate: " + numbers[i]);
}
}
i suppose that you want to compare for example the number 12345 with 23145, and prompt out a false, and if they are the same (digit by digit, prompt a true) , am i right?.
If you want to do this, you should make 2 arrays and you have to make sure to compare each position of both so you can compare digit by digit.
Hope it helps you
public boolean unique(int theNumber) {
String number = new Integer(theNumber).toString();
Set<Character> set = new LinkedHashSet<Character>();
for(char c:number.toCharArray()) {
set.add(Character.valueOf(c));
}
return number.length() == set.size();
}