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.
Related
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 am writing one java program. Arthur defines a function f(k) to be the number of (p,q) pairs such that:
1< p <= q <= k
p and q are coprimes
p.q=k
I am supposed to write one program for a given integer n and help Arthur find and print the result of (Σ k=1 to n) f(k)
Constraints:
1<=n<=pow(10,9)
For e.g
(Input)Let's say n = 12
For the value of f(k) for 1<=k<=12
For k=6 there is one valid pair (2,3), so f(6) = 1
For k=10 there is one valid pair (2,5), so f(10) = 1
For k=12 there is one valid pair (3,4), so f(12) = 1
For all other 1<=k<=12 the function return 0
So, other final sum is the result of 1+1+1 = 3 (Final output)
Here is my code:
import java.util.Scanner;
class ArthurFunction{
public static boolean areCoPrime(int a, int b){
int max = 0;
boolean flag = true;
if(a>=b)
max = a;
else
max = b;
for(int i=2;i<=max;i++)
if((a%i==0)&&(b%i==0))
flag = false;
return flag;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int sum = 0;
for(int k = 1;k<=n;k++){
for(int p=2;p<=k;p++){
for(int q=2;q<=k;q++){
if(areCoPrime(p,q)&&(p*q==k)&&(p<=q))
sum+=sum;
}
}
}
System.out.println(sum);
}
}
When I run this code the output should be 3 but I am getting 0 and also unable to find the solution.
You can improve your program by
Making a faster areCoPrime() method
Decrease the number of nested loops in main()
For (1), we know 2 numbers are coprime when their greatest common divisor (GCD) is 1. Their is an efficient method to find GCD called Euclidean algorithm.
For (2), you can remove the 3rd loop, p in the 2nd loop only need to go to sqrt(k)
Refer to my revised code below (Tested: n = pow(10,6) runs less than 2 secs on my PC)
import java.util.Scanner;
class ArthurFunction{
public static boolean areCoPrime(int a, int b){
if (GCD(a,b)==1) return true;
return false;
}
public static int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int sum = 0;
for(int k=1;k<=n;k++){
for(int p=2;p*p<k;p++){
if(k%p==0) {
int q = k/p;
if (areCoPrime(p,q)) sum++;
}
}
}
System.out.println(sum);
}
}
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
I'm new to Java. I found a website called project eulder and was practicing on a problem.
I don't understand why the following program does not display anything but when I put System.out.println(max); into the for loop it works but displaying all the prime numbers including the biggest. Who do I only the display the biggest prime number?
public class LargestPrimeFactor {
public static void main(String[] args) {
long x = 600851475143L;
int max = 0;
for (int i = 1; i <= x; i++) {
if (x % i == 0)
if (isPrime(i))
max = i;
}
System.out.println(max);
}
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}
}
You have written an infinite loop: 600851475143L is greater than the maximum value that can be stored in an int, so i <= x will always be true.
Changing i and all the other relevant variables to long may solve this issue, but you'll still have to rethink your algorithm. Checking if 600851475143 numbers are prime is just going to take too long.
Hint: once you have found a number that divides x, you can divide x by that number... (Hope this doesn't spoil the fun)
I was given a homework assignment in Java to create classes that find Prime number and etc (you will see in code better).
My code:
class Primes {
public static boolean IsPrime(long num) {
if (num%2==0){
return false;
}
for (int i=3; i*i<=num;i+=2) {
if (num%i==0) {
return false;
}
}
return true;
} // End boolen IsPrime
public static int[] primes(int min, int max){
int counter=0;
int arcount=0;
for (int i=min;i<max;i++){
if (IsPrime(i)){
counter++;
}
}
int [] arr= new int[counter];
for (int i=min;i<max;i++){
if (IsPrime(i)){
arr[arcount]=i;
arcount++;
}
}
return arr;
} // End Primes
public static String tostring (int [] arr){
String ans="";
for (int i=0; i<arr.length;i++){
ans= ans+arr[i]+ " ";
}
return ans;
}
public static int closestPrime(long num){
long e = 0 , d = 0 , f = num;
for (int i = 2; i <= num + 1 ; i++){
if ((num + 1) % i == 0){
if ((num + 1) % i == 0 && (num + 1) == i){
d = num + 1;
break;
}
num++;
i = 1;
}
}
num = f;
for (int i = 2; i < num; i++){
if ((num - 1) % i == 0){
if ((num - 1) % i == 0 && (num - 1) == i){
e = num - 1;
break;
}
num--;
i = 1;
}
}
num = f;
if (d - num < num - e) System.out.println("Closest Prime: "+d);
else System.out.println("Closest Prime: "+e);
return (int) num;
} // End closestPrime
}//end class
The goal of my code is to be faster (and correct). I'm having difficulties achieving this. Suggestions?
**New code:
class Primes {
public static boolean IsPrime(int num) {
if (num==1){
return false;
}
for (int i=2; i<Math.sqrt(num);i++) {
if (num%i==0) {
return false;
}
}
return true;
}
// End boolen IsPrime
public static int[] primes(int min, int max){
int size=0;
int [] arrtemp= new int[max-min];
for (int i=min;i<max;i++){
if (IsPrime(i)){
arrtemp[size]=i;
size++;
}
}
int [] arr= new int[size];
for (int i=0;i<size;i++){
arr[i]=arrtemp[i];
}
return arr;
}
public static String tostring (int [] arr){
String ans="";
for (int i=0; i<arr.length;i++){
ans= ans+arr[i]+ " ";
}
return ans;
}
public static int closestPrime(int num) {
int count=1;
for (int i=num;;i++){
int plus=num+count, minus=num-count;
if (IsPrime(minus)){
return minus;
}
if (IsPrime(plus)) {
return plus;
}
count=count+1;
}
} // End closestPrime
}//end class
I did try to make it a bit better. what do you think, it can be improved more? (the speed test is still high...)
In your primes function you:
Check if the current number is divisible by two
Check to see if it's prime
Create an array to put your output in.
Check every number in the range again for primality before putting it in your array.
The problem is in the last step. By double-checking whether each number is prime, you're duplicating your most expensive operations.
You could use a dynamic data structure and add prime numbers to it as you find them. That way you only need to check once.
Alternatively, you could create a boolean array which is the size of your input range. Then as you find primes, set the corresponding array value to true.
UPDATE:
There are still a number of improvements you can make, but some will require more work than others to implement. Look at the specifics of your test and see what fits your needs.
Low-hanging fruit:
Use an ArrayList to collect primes as you find them in primes, as opposed to looping over the values twice.
In closestPrime, you're checking every single value on either side of num: half of these are even, thus not prime. You could adapt your code to check only odd numbers for primality.
Trickier to implement:
Try a more advanced algorithm for IsPrime: check out the Sieve of Eratosthenes
Above all, you should spend some time figuring out exactly where the bottlenecks are in your code. Oftentimes performance problems are caused by code we thought was perfectly fine. You might consider looking into the code-profiling options available in your development environment.
You make quite a few calls to isPrime(), each of which is very expensive. Your first step should be to minimize the number of times you do that, since the result doesn't change for any given number, there's no point calling more than once. You can do this with memoization by storing the values once they're computed:
ArrayList<Integer> memoList = new ArrayList<Integer>();
for(int i = 0; i < max; i++) {
if(isPrime(i)) {
memoList.add(i);
}
}
Now memoList holds all the primes you need, up to max, and you can loop over them rapidly without needing to recompute them every time.
Secondly, you can improve your isPrime() method. Your solution loops over every odd number from 3 to sqrt(n), but why not just loop over the primes, now that we know them?
public static boolean IsPrime(long num) {
for(int p : memoList) {
if(num % p == 0) {
return false;
}
}
return true;
}
These changes should dramatically improve how quickly your code runs, but there has been a lot of research into even more efficient ways of calculating primes. The Wikipedia page on Prime Numbers has some very good information on further tactics (prime sieves, in particular) you can experiment with.
Remember that as this is homework you should be sure to cite this page when you turn it in. You're welcome to use and expand upon this code, but not citing this question and any other resources you use is plagiarism.
I see a couple problems with your answer. First, 2 is a prime number. Your first conditional in IsPrime breaks this. Second, in your primes method, you are cycling through all number from min to max. You can safely ignore all negative numbers and all even numbers (as you do in IsPrime). It would make more sense to combine these two methods and save all the extra cycles.