I'm trying to get a program to get me the prime numbers from a certain range (user inputs the maximum number) and this variable called maxNumber will be used to stop the while loop. The control variable used starts at the first prime number 2 and is called i and will be used to print out the prime numbers (when found) and natural numbers, respectively.
My problem is that I'm not really sure if my algorithm inside the main method and mutator method are both correct and I have a problem where I am putting the user input (the max number) but nothing is happening at all after that -- basically, it is compiling and running but not responding when inputting the first variable.
Help would very much be appreciated !
import java.util.*;
public class PrimeCalculator {
private static int maxNumber;
private static int divisibleCount;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int i = 2;
System.out.println("Enter the maximum amount of numbers you want to find prime numbers within: ");
maxNumber = scanner.nextInt();
while(i <= maxNumber)
isPrime(i);
if(divisibleCount < 2)
System.out.println(i + " is a prime number");
if(divisibleCount > 2)
System.out.println(i + " is not a prime number.");
divisibleCount = 0;
i++;
}
public static void isPrime(int n) {
divisibleCount = 0;
for(int x = 1; x <= maxNumber; x++ )
if(n%x == 0)
divisibleCount++;
}
}
Although I do not think it is clear what you're asking, I will make a few suggestions.
First of all, at your main method, change if(divisibleCount < 2) to if(divisibleCount <= 2) because primes are divided by 1 and themselves (so, "divisibleCount" is 2).
Also, in your while loop, you should check if i equals one and say that it is not a prime.
As said in the comments, at the isPrime method , you can change the loop to for(int x = 1; x <=n; x++ ) as it is impossible for a number to be perfectly divided by soomething greater (i.e. 6 divided by 10 cannot have modulo 0)
EDIT: As dcsohl suggested, it is even better to have for(int x = 1; x <= Math.sqrt(n); x++) (see comment)
Check your syntax. At the while loop, you do not open and close brackets, so only isPrime(i) gets executed in the loop. Imagine
while(i <= maxNumber){
isPrime(i);
}
if(divisibleCount < 2) // ....etc
And since i is never incremented in the loop, it it always 2, so ... we have got an infinite loop!
(General improvement) Surround the maxNumber = scanner.nextInt(); in a try-catch block to avoid crashing when entering say, a string instead of an int.
These are the problems I found, hope I helped you.
PS. If you have any other question like this (i.e. general code checking), you should ask them at Code Review rather than Stack Overflow
I won't answer your Java questions, but the normal algorithm for enumerating the prime numbers is the Sieve of Eratosthenes, invented by a Greek mathematician over two thousand years ago:
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n
if sieve[p]
output p # prime
for i from p*p to n step p
sieve[i] := False
This algorithm examines every number p from 2 to n; if p is prime, the loop on i marks False all the multiples of p; the i loop starts from the square of p because all smaller multiples will already have been marked False by smaller primes.
If you're interested in programming with prime numbers, I modestly recommend this essay at my blog.
import java.io.*;
class Prime
{
public static void main(String args[])
{
long i,j,n=1000000100000L;
long sum=0;
long i1=1000000000000L;
long c;
System.out.println("The Prime Numbers are:");
for(i=i1;i<=n;i++)
{
c=0;
for(j=2;j<=10000000;j++)
{
if(i%j==0)
c=c+1;
if(c==1)
break;
}
if(c==0)
{
System.out.println(i);
sum=sum+i;
}
}
System.out.println("The Sum of Prime numbers are:"+sum);
}
}
Related
I was looking over this on YouTube and saw some code. I got most of it but didn't understand at all the reason why you the value n divide by two. Could someone please explain it?
import java.util.ArrayList;
public class Primes {
public static void main(String[] args) {
System.out.println(findPrimes(1, 100));
}
public static ArrayList<Integer> findPrimes(int start, int end) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for(int n = start; n < end; n++) {
boolean prime = true;
int i = 2;
while(i <= n/2) {
if(n % i == 0) {
prime = false;
break;
}
i++;
}
if(prime) {
primes.add(n);
}
}
return primes;
}
}
A number can only be divided by a number that is less than or equal to its half. Or the number to be divided itself.
Here, we are checking till n/2 so that the number of iterations and the load on the system reduces and make the program more efficient. Since the greatest factor which can divide a number (excluding itself) is half of the number, we check only till that point. There is no point of checking beyond that.
It's an attempt to improve the efficiency of the solution by stopping the loop at a point where the algorithm will no longer find any more prime factors.
However, it's suboptimal. If n == a * b and a <= b, a can be no higher than the square root of n. Therefore, checking for i <= Math.sqrt(n) would eliminate many more unnecessary iterations of the loop for large values of n.
A further improvement could be made by iterating over known values of primes instead of incremental values of i, since once you've established that a number isn't divisible by 3 there's no point checking 6, 9, 12 and so on.
fist thing first , the code :
package com.company;
import java.util.Scanner;
public class index {
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
//let a= 2 7 4
int b= a%10;//4
int c=a/10;//27
int d= c%10;//7
int e=c/10;//2
//e=first num;
//d=middle num;
//b= last num ;
// for searching the greatest number
if (d>e && d>b )
System.out.printf(" the greatest number is %d%d%d",d,e,b);
else if(e>d && e>b )
System.out.printf(" the greatest number is %d%d%d",e,d,b);
else if (b>e && b>d )
System.out.printf(" the greatest number is %d%d%d",b,e,d);
// for the smallest number
else if(d<e && d<b && b>e)
System.out.printf(" the smallest number is %d%d%d",b,e,d);
else if(d<e && d<b && e>b)
System.out.printf(" the smallest number is %d%d%d",e,b,d);
else if (e<d && e<b && b>d)
System.out.printf(" the smallest number is %d%d%d",b,d,e);
else if(e<d && e<b && d>b)
System.out.printf(" the smallest number is %d%d%d",d,b,e);
else if (b<e && b<d && e>d)
System.out.printf(" the smallest number is %d%d%d",e,d,b);
else
System.out.printf(" the smallest number is %d%d%d",d,e,b);
}
}
now the problem:
this code is make to take number from the user as the input **of any three digit number ** and change it to the greatest number and smallest number ,
for example:
input number =274
output :
greatest number=742
smallest number=247
the above code is giving the greatest number but not the smallest number and the code is very lengthy ,
my output:
enter any three digit number
546
the greatest number is 654
so please help ,any error in code and if there is any short code then please help
I think that the problem is in the way of solution. As for me that is better to use some array or list and sort it. Something like that
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int[] array = new int[3];
for (int i = 0; i < 3; i++) {
array[i] = a % 10;
a = a / 10;
}
Arrays.sort(array);
int smallest = 0;
int greatest = 0;
for (int i = 0; i < 3; i++) {
smallest += array[i];
if (i != 2) {
smallest *= 10;
}
}
for (int i = 2; i > -1; i--) {
greatest += array[i];
if (i != 0) {
greatest *= 10;
}
}
System.out.println(Arrays.toString(array));
System.out.println(smallest);
System.out.println(greatest);
}
May I suggest a whole different approach?
void printGreatestAndSmallest(int number) {
char[] digits = String.valueOf(number).toCharArray();
Arrays.sort(digits);
String smallest = new String(digits);
String greatest = new StringBuilder(smallest).reverse().toString();
System.out.println("Greatest number is " + greatest);
System.out.println("Smallest number is " + smallest);
}
What happens here, is that we convert the digits to a char[], which can be sorted using Arrays.sort(...). This way, the smallest digit comes in front, the largest at the end. The char[] is converted back to a string with the String(char[]) constructor.
That is the smallest value. The largest value is the reverse of it! We can get the largest number using StringBuilder's reverse() method.
Note that this code cannot handle negative numbers.
The problem with your current approach is that it contains a lot of repetitions, and is not quite flexible; it is bound to an input of exactly three digits.
In order to fix the issue your are facing, remove the else keyword from the line else if(d<e && d<b && b>e). Each if-elseif-else statement only executes a single branch, but you need two branches to be executed, one for the smallest number, and one for the greatest number.
Further:
Use descriptive variable names. You have a comment in your code:
//e=first num;
//d=middle num;
//b= last num ;
but why don't you rename e, d and b to firstDigit, middleDigit and lastDigit respectively?
Follow the Java Naming Conventions. Variable and method names are written in camelCase, and class names in PascalCase. So class index should be class Index. Also make sure to rename index.java to Index.java.
You are defining variables with almost the same function: in your case firstNum, middleNum and lastNum. They all allow to store a specific digit of the input number. In such a case, you should use an array instead of separate variables. Loops work well with arrays.
If your code somehow iterates over all possible permutations of some collection, using if-else statements, that is probably not the best way.
For example:
if (d>e && d>b )
else if(e>d && e>b )
else if (b>e && b>d )
You should ask yourself: should these digits be in a certain order? The answer here is yes, they need to be sorted from low to high (and high to low). In that case, you probably want to sort them.
I'm kind of a newbie at Java, and not very good at it. It's a trial and error process for me.
I'm working on a Java program to output the amount of primes in an array. I can get it to output the primes, but I want to also output the quantity of primes. I tried to add each prime to an array list titled "primes" then return "primes.size()" at the end of my program. It doesn't work as intended. The count is actually off. When I create an array of 5 numbers, it outputs 3 primes, 2, 3, and 5. But then it says I have 4 primes. I think it might be counting 1 as a prime. Because when I create an array of 20, the prime numbers output 2,3,5,7,11,13,17 and 19. Then it says the total prime numbers = 9. It should be 8 though.
Here's my code
public class Prime {
public static void main(String[] args) {
int index = 0;
Scanner scan = new Scanner(System. in );
System.out.println("How big would you like the array? ");
int num = scan.nextInt();
int[] array = new int[num];
ArrayList < Integer > primes = new ArrayList < Integer > ();
//System.out.println("How Many threads? ");
//int nThreads = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
//Thread[] thread = new Thread[nThreads];
for (int n = 1; n <= array.length; n++) {
boolean prime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(n);
}
if (prime && n != 1) {
System.out.println(n + "");
}
}
System.out.println("Total Prime numbers = " + primes.size());
System.out.println("Prime Numbers within " + array.length);
}
}
Forgive the sloppiness of it. I actually plan on adding multithreading to it, but I wanted to get this down first.
Any help would be greatly appreciated. Thanks.
You have included 1 in your array of primes, because you started the n for loop at 1. You don't print it because of the final if statement, but it's there in the ArrayList.
Start your n for loop with n = 2. As a consequence, you won't need the final if statement, because n won't be 1 ever. You could print the prime at the same time as you add it to the ArrayList.
I got an assignment to create a program which displays the perfect integers between one and 100. Here is the actual assignment:
Create a PerfectIntegers application that displays all perfect integers up to 100. A perfect integer is a number which is equal to the sum of all its factors except itself. For example, 6 is a perfect number because 1 + 2 + 3 = 6. The application should include a boolean method isPerfect().
I tried and came up with this:
import java.util.ArrayList;
public class PerfectIntegers {
public static boolean isPerfect(int a){
ArrayList<Integer> factors = new ArrayList<Integer>();
int sum=0;
boolean is;
for (int i=1; i<=100; i++){
double r=a/i;
if (r%1==0){
factors.add(i);
}
}for (int i=0;i<factors.size();i++){
sum+=factors.get(i);
}if (sum==a){
is=true;
}else{
is=false;
}return is;
}
public static void getInts(){
for (int i=2; i<=100; i++){
boolean is=isPerfect(i);
if (is!=false){
System.out.print(i+" ");
}
}
}
public static void main(String[] args) {
getInts();
}
}
Eclipse did not show any errors but when I try to run it, the program is terminated and I get nothing.
The problem is likely with double r, as it is not dividing properly 100% of the time.
Your factorization code is wrong. You can fix it like this:
for (int i = 1 ; i < a; i++) {
if (a % i == 0) {
factors.add(i);
}
}
One reason your old code did not work is that you misunderstood the workings of the % operator. It computes the remainder of the division of the left-hand side by the right-hand side, so r % 1 == 0 will be true for all numbers, because 1 divides everything; r % 2 == 0 is a way to detect even numbers, and so on.
The other reason is that you went all the way to 100 in search of divisors. This necessarily includes a, which automatically puts the total above the number itself, because 1 is already on the list.
Once you get this working, you could simplify the code by dropping the list of factors. Since the sum of all factors is all that you need, you might as well compute it in the factorization loop, and drop the loop that follows it:
sum = 0;
for (int i = 1 ; i < a; i++) {
if (a % i == 0) {
sum += i;
}
}
dasblinkenlight has already provided the correct answer. Let me just add that since this seems to be a (potentially graded) assignment you might consider refactoring the getInts() method as well.
boolean is=isPerfect(i);
if (is!=false){
System.out.print(i+" ");
}
is actually equal to
if (isPerfect(i)){
System.out.print(i+" ");
}
since isPerfect() already returns a boolean that can be used inside the condition of the if-statement.
It can be argued (even though I strongly disagree in this concrete case) that it might be more readable to first store the return value in a variable like in in the first variation. But even then you should never have to check for
if (is!=false) { //...
but should be using
if (is) { // ...
instead.
So the riddle is:
John has written down k sequential odd numbers: n{1}, n{2}, ..., n{k-1}, n{k} (where n{2} = n{1} + 2 and so on). We know that:
The sum of the first four numbers is a fourth power of some prime number (so n{1} + n{2} + n{3} + n{4} = p{1} where p{1}^4 is a prime number.
The sum of the last five numbers is a fourth power of some prime number (so n{k} + n{k-1} + n{k-2} + n{k-3} + n{k-4}= p{2}^4 where p{1} is a prime number.
The question is - how many numbers have been written down (k=?).
Below is my attempt to solve it in Java:
import java.math.BigInteger;
import java.util.Set;
//precalculate prime numbers
public class PrimeSieve {
public static boolean[] calculateIntegers(int N) {
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
return isPrime;
}
}
The solving class:
public class Solver {
static boolean[] isPrime = PrimeSieve.calculateIntegers(100000);
public static void main(String[] args) {
int minNumberCount = 5;
int maxNumberCount = 2000;
int startInt = 2;
int endInt = 1000000;
for (int numberCount = minNumberCount; numberCount < maxNumberCount+1; numberCount++) {
System.out.println("Analyzing for " + numberCount + " numbers");
int[] numbers = new int[numberCount];
//loop through number sets
for (int firstNum = startInt; firstNum < endInt; firstNum+=2) {
//populate numbers array
for(int j=0; j<numberCount; j++){
numbers[j] = firstNum + j*2;
}
long bottomSum=0;
long topSum=0;
//calculate bottom sum
for(int iter=0; iter<4; iter++){
bottomSum+=numbers[iter];
}
//calculate top sum
for(int iter=numberCount-1; iter>numberCount-6; iter--){
topSum+=numbers[iter];
}
//check if the sums match the sulution criteria
if(checkPrime(quadRoot(bottomSum)) && checkPrime(quadRoot(topSum))){
System.out.println("SOLUTION!");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.exit(0);
}
}
}
}
private static boolean checkPrime(int i){
return isPrime[i];
}
private static boolean checkPrime(double i){
return ((i % 1) == 0) && checkPrime((int) i);
}
private static double quadRoot(long n){
return Math.sqrt(Math.sqrt(n));
}
}
Using this algorithm with the assumed parameters (max k=2000, max n{1}=100000) - I've found no solution. My question is: are the parameter assumptions wrong (no solution in this range), or do I have some algorithmic/numeric error and that is the reason I've found no solution?
EDIT: sorry - my mistake - it should be ODD instead of EVEN.
It is still easier to solve this directly than to write a program.
The first sum is even so it must be 16 (since 2 is the only even prime). The first four numbers are therefore 1,3,5,7.
The sum of five consecutive odd numbers is 5 times the middle number hence must be divisible by 5. Since it is a fourth power of a prime it must be 625 and the last five numbers are therefore 121,123,125,127,129
It is now an easy task to determine k=65
As said in the comments, your riddle has no solution.
Let's suppose there was a solution, then n1 + n2 + n3 + n4 == p1^4 . We know that n1,n2,n3,n4 are even from the definition of the riddle and therefore as a sum of even numbers, n1 + n2 + n3 + n4 is even as well. This leads us to the fact that p1^4 is even. We know that a multiplication of two odd numbers results only an odd number, hence p1^4 = p1 * p1 * p1 * p1 means that p1 must be an even number. However, p1 is prime. The only prime number which is also even is 2. It's easy to see that there are no four consecutive even numbers that sum up to 16 and therefore p1 is not prime. This contradicts the assumption that p1 is a prime, hence, no solution.
If there are only even numbers, the sum of those is an even number. If I understood correctly, your sum has to be the result of the fourth power of a prime number. Considering the sum is an even number, the only number to satisfy your condition is 16 (2*2*2*2), where 2 is a prime number, so your sum of 4 even number has to be 16. Now, if you're certain there's a sequence, then the sum is computed by adding the first and the last number in the sequence, then multiplying the result with the number of elements in the sequence, and dividing the result of the multiplication by 2. For example, 2+4+6+8=(2+8)*4/2=10*4/2=20. Similarly, for your example, n{1}+n{2}+...+n{k}=(n{1}+n{k})*k/2
On a side note, your smallest sum of 4 even numbers (20), the example I used, is already above your only 4th power of the prime number (16), so yes, there is no valid example in your sequence.
I hope this made some sense