Display all prime numbers based on range inputted in java - java

I am trying to solve a sample exercise which is to display Prime numbers based on the range inputted. For example if I inputted 10 it should output 2 3 5 7 11 13 17 19 23 29.
Here is my code:
System.out.print("Enter Range: ");
int range = input.nextInt();
int r = 0;
for(int ctr1 = 2; ctr1 <= range; ctr1++){
for(int ctr2 = 1; ctr2 <= ctr1; ctr2++){
if(ctr1%ctr2 == 0){
r++;
}
}
if(r == 2){
System.out.println(ctr1);
}
}
What happens is when I input 10 it just outputs 2. Can anyone please tell me the error in my codes?
Thanks...

Using nested loop in this case could make things more complicated. I would suggest you to divide the solution into two steps:
create a function to determine if a number is prime.
private static boolean isPrime(int n) {
//check if n is a multiple of 2
if (n % 2 == 0) return false;
//if not, then just check the odds
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return false;
}
return true;
}
find the first N prime numbers with a loop:
System.out.print("Enter Range: ");
int range = input.nextInt();
int count = 0;
for (int number = 2; count < range; number++) {
if (isPrime(number)) {
count++;
System.out.println(number);
}
}

I didnt understand your code. Try to give reasonable parameter names. Anyway this the code that you are looking for.
public static void main(String args[]) {
//get input till which prime number to be printed
System.out.println("Enter the amount of prime numbers to be printed: ");
int limit = new Scanner(System.in).nextInt();
int count=1;
//printing primer numbers till the limit ( 1 to 100)
System.out.println("Printing prime number from 1 to " + limit);
for(int number = 2; count<=limit; number++){
//print prime numbers only
if(isPrime(number)){
System.out.println(number);
count++;
}
}
}
/*
* Prime number is not divisible by any number other than 1 and itself
* #return true if number is prime
*/
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}

One more solution)
public static boolean checkPrime(int i) {
if (i <= 1)
return false;
else if (i <= 3)
return true;
else if (i % 2 == 0 || i % 3 == 0)
return false;
int n = 5;
while (n * n <= i) {
if (i % n == 0 || i % (n + 2) == 0)
return false;
n = n + 6;
}
return true;
}
public static void main(String[] args) throws Exception {
int isPrime = 0;
int counter = 0;
int size = 10;
while (isPrime < size) {
counter++;
if (checkPrime(counter)) {
isPrime++;
System.out.println(counter);
}
}
}

Related

I'm trying to print out prime number but not sure what's wrong with my code

My code
void printPrimes (int max) {
boolean prime;
for (int n = 2; n < max; n++){
prime = true;
double maxF;
maxF = Math.sqrt(n);
for (int f = 2; f < maxF; f++) {
if (n % f == 0) {
prime = false;
}
}
if (prime == true) {
System.out.println(n + " is prime");
}
}
}
This the result I get
4 is prime
5 is prime
6 is prime
7 is prime
8 is prime
9 is prime
10 is prime
11 is prime
what do I do to fix this issue
Debug your code. As in, take out a pen, be the computer. You answer, without running this code, what it should do. Then check what it actually does with a debugger (or sysout statements if you must). There where you find a difference, you found a bug.
For example, Math.sqrt(4), what's that? is 2 less than 2?
Change your conditional in your loop
for (int f = 2; f <= maxF; f++) { // should be <= maxf
if (n % f == 0) {
prime = false;
}
}
at least replace f < maxF with f*f <= max
Because loop maximum should be less or equals to
Math.sqrt(number)
public class Main {
public static void main(String[] args) {
printPrimes(20);
}
static void printPrimes (int max) {
for(int i=2;i<=max;i++){
if(isPrime(i)){
System.out.println(i+" is prime");
}
}
}
static boolean isPrime(int number) {
if(number < 2){
return false;
}
for(int i=2;i<=Math.sqrt(number);i++){
if(number % i == 0){
return false;
}
}
return true;
}
}

Finding the smith number between given range

I will get to the point quickly. Basically smith numbers are: Composite number the sum of whose digits is the sum of the digits of its prime factors (excluding 1). (The primes are excluded since they trivially satisfy this condition). One example of a Smith number is the beast number 666=2·3·3·37, since 6+6+6=2+3+3+(3+7)=18.
what i've tried:
In a for loop first i get the sum of the current number's(i) digits
In same loop i try to get the sum of the number's prime factors digits.
I've made another method to check if current number that is going to proccessed in for loop is prime or not,if its prime it will be excluded
But my code is seems to not working can you guys help out?
public static void main(String[] args) {
smithInrange(1, 50);
}
public static void smithInrange(int start_val, int end_val) {
for (int i = start_val; i < end_val; i++) {
if(!isPrime(i)) { //since we banned prime numbers from this process i don't include them
int for_digit_sum = i, digit = 0, digit_sum = 0, for_factor_purpose = i, smith_sum = 0;
int first = 0, second = 0, last = 0;
// System.out.println("current number is" + i);
while (for_digit_sum > 0) { // in this while loop i get the sum of current number's digits
digit = for_digit_sum % 10;
digit_sum += digit;
for_digit_sum /= 10;
}
// System.out.println("digit sum is"+digit_sum);
while (for_factor_purpose % 2 == 0) { // i divide the current number to 2 until it became an odd number
first += 2;
for_factor_purpose /= 2;
}
// System.out.println("the first sum is " + first);
for (int j = 3; j < Math.sqrt(for_factor_purpose); j += 2) {
while (for_factor_purpose % j == 0) { // this while loop is for getting the digit sum of every prime
// factor that j has
int inner_digit = 0, inner_temp = j, inner_digit_sum = 0;
while (inner_temp > 0) {
inner_digit = inner_temp % 10;
second += inner_digit;
inner_temp /= 10;
}
// System.out.println("the second sum is " + second);
for_factor_purpose /= j;
}
}
int last_temp = for_factor_purpose, last_digit = 0, last_digit_sum = 0;
if (for_factor_purpose > 2) {
while (last_temp > 0) {
last_digit = last_temp % 10;
last += last_digit;
last_temp /= 10;
}
// System.out.println("last is " + last);
}
smith_sum = first + second + last;
// System.out.println("smith num is "+ smith_sum);
// System.out.println(smith_sum);
if (smith_sum == digit_sum) {
System.out.println("the num founded is" + i);
}
}
}
}
public static boolean isPrime(int i) {
int sqrt = (int) Math.sqrt(i) + 1;
for (int k = 2; k < sqrt; k++) {
if (i % k == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
the output is:
the num founded is4
the num founded is9
the num founded is22
the num founded is25
the num founded is27
the num founded is49
how ever the smith number between this range(1 and 50) are:
4, 22 and 27
edit:I_ve found the problem which is :
Math.sqrt(for_factor_purpose) it seems i should add 1 to it to eliminate square numbers. Thanks to you guys i've see sthe solution on other perspectives.
Keep coding!
Main loop for printing Smith numbers.
for (int i = 3; i < 10000; i++) {
if (isSmith(i)) {
System.out.println(i + " is a Smith number.");
}
}
The test method to determine if the supplied number is a Smith number. The list of primes is only increased if the last prime is smaller in magnitude than the number under test.
static boolean isSmith(int v) {
int sum = 0;
int save = v;
int lastPrime = primes.get(primes.size() - 1);
if (lastPrime < v) {
genPrimes(v);
}
outer:
for (int p : primes) {
while (save > 1) {
if (save % p != 0) {
continue outer;
}
sum += sumOfDigits(p);
save /= p;
}
break;
}
return sum == sumOfDigits(v) && !primes.contains(v);
}
Helper method to sum the digits of a number.
static int sumOfDigits(int i) {
return String.valueOf(i).chars().map(c -> c - '0').sum();
}
And the prime generator. It uses the list as it is created to determine if a given
number is a prime.
static List<Integer> primes = new ArrayList<>(List.of(2, 3));
static void genPrimes(int max) {
int next = primes.get(primes.size() - 1);
outer:
while (next <= max) {
next += 2;
for (int p : primes) {
if (next % p == 0) {
continue outer;
}
if (p * p > next) {
break;
}
}
primes.add(next);
}
}
}
I do not want to spoil the answer finding, but just some simpler code snippets,
making everything simpler, and more readable.
public boolean isSmith(int a) {
if (a < 2) return false;
int factor = findDivisor(a);
if (factor == a) return false;
int sum = digitSum(a);
// loop:
a /= factor;
sum -= digitSum(factor);
...
}
boolean isPrime(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return false;
}
}
return true;
}
int findDivisor(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return i;
}
}
return a;
}
int digitSum(int a) {
if (a < 10) {
return a;
}
int digit = a % 10;
int rest = a / 10;
return digit + digitSum(rest);
}
As you see integer division 23 / 10 == 2, and modulo (remainder) %: 23 % 10 == 3 can simplify things.
Instead of isPrime, finding factor(s) is more logical. In fact the best solution is not using findDivisor, but immediately find all factors
int factorsSum = 0;
int factorsCount = 0;
for(int i = 2; i*i <= a; i++) {
while (a % i == 0) {
factorsSum += digitSum(i);
a /= i;
factorsCount++;
}
}
// The remaining factor >= sqrt(original a) must be a prime.
// (It cannot contain smaller factors.)
factorsSum += digitSum(a);
factorsCount++;
Here is the code. If you need further help, please let me know. The code is pretty self explanatory and a decent bit was taken from your code but if you need me to explain it let me know.
In short, I created methods to check if a number is a smith number and then checked each int in the range.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
System.out.println(smithInRange)
}
public int factor;
public boolean smithInRange(int a, int b){
for (int i=Math.min(a,b);i<=Math.max(a,b);i++) if(isSmith(i)) return true;
return false;
}
public boolean isSmith(int a){
if(a<2) return false;
if(isPrime(a)) return false;
int digits=0;
int factors=0;
String x=a+¨" ";
for(int i=0;i<x.length()-1;i++) digits+= Integer.parseInt(x.substring(i,i+1));
ArrayList<Integer> pF = new ArrayList<Integer>();
pF.add(a);
while(!aIsPrime(pF)){
int num = pF.get(pF.size-1)
pF.remove(pF.size()-1);
pF.add(factor);
pF.add(num/factor)
}
for(int i: pF){
if((factors+"").length()==1)factors+= i;
else{
String ss= i+" ";
int nums=0;
for(int j=0;j<ss.length()-1;j++){
nums+=Integer.parseInt(ss.substring(j,j+1));
}
}
}
return (factors==digits);
}
public boolean isPrime(int a){
for(int i=2;i<=(int)Math.sqrt(a),i++){
String s = (double)a/(double)i+"";
if(s.substring(s.length()-2).equals(".0")){
return false;
factor = i;
}
}
return true;
}
public boolean aIsPrime(ArrayList<int> a){
for(int i: a) if (!isPrime(a)) return false;
return true;
}
}

Trying to see if the number user entered is prime in java

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = 0;
do {
System.out.println("How long should we search for primes? Until N=: ");
N = scan.nextInt();
} while (N <= 2); // gets the amount of prime numbers there are that go up to that number
//example, if user enters 20, the output will be that there are 8 prime numbers
boolean[] prime = new boolean[N +2];
for (int i = 2; i <= N; i++) {
prime[i] = true; //makes all values in the array true
}
for (int i = 2; i * i <= N; i++) {
if (prime[i]) {
for (int z = i; z * i <= N; z++) {
prime[i * z] = false; // makes the non prime numbers in the array false
int newCheck = 0;
do {
System.out.println("Enter a number to see if it is prime");
int go = 0;
newCheck = scan.nextInt(); //here's where i need help
} while (newCheck <= 1 || newCheck > N);
if(prime[newCheck]){ // if the number entered is true in the array, it is prime
System.out.println("It is prime");
int mPrime=(int)((Math.log(newCheck))/(Math.log(2)))-1;
if (prime[mPrime]){//ignore this, its for another part i need to do
System.out.println(""+newCheck+ "is a merseinne prime number! It equals 2^"+mPrime+ " -1");
}
}
else if (prime[newCheck]==prime[i*z]){ //if the number is equal to false in the array,
//it is not prime
System.out.println("It is not prime");
}
if(newCheck==0){
break;
}
}
}
}
int counterPrime = 0;
for (int i = 2; i <= N; i++) {
if (prime[i]) {
counterPrime++;
}
}
System.out.println("The number of primes less than or equal to " + N + " is " + counterPrime);
}
I need help with trying to output to the user that the number they entered is prime. So far this example only works for some numbers. The program thinks 14 is prime, 12 is prime, 25 is prime, 35 is prime,36 is prime,39 is prime,and that 34 is prime.
It gets some numbers right though. It knows 8, 10, 12,18 and some other numbers are not prime.
Here is a little method to help you along:
public static boolean isPrime(final int number) {
int temp;
boolean isPrim = true;
for(int i=2; i <= number / 2; i++) {
temp = number%i;
if(temp==0) { isPrim = false; break; }
}
return isPrim;
}
Hope this helps.

Find Prime Numbers

I am trying to take two arguments from the command line, the first number is the starting point, and the second one is how many prime numbers should be found after that. I need to print the prime numbers found as many times as the second command argument says. I cannot figure out how to make it run the correct amount of times, and after that find the prime number. Here is what I have tried:
int values = Integer.parseInt(args[0]);
int loopAmount = Integer.parseInt(args[1]);
for (int i = 2; i <= loopAmount; i++) {
loopAmount++;
if (values % i != 0) {
values++;
System.out.println(i);
}
}
Your main loop should be something like this:
int start = Integer.parseInt(args[0]);
int count = Integer.parseInt(args[1]);
for (int candidate = start, i = 0; i < count; ++candidate) {
if (isPrime(candidate)) {
i++;
System.out.println(candidate);
}
}
I replaced the variable names to make them more meaningful about their purpose.
Inside the loop, the isPrime method is something you'll have to implement: if the parameter it receives is a prime, return true, otherwise false.
If I understand correctly you want to find N prime numbers starting from X. Code should be pretty simple:
int X = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int C = 0;
while (C < N)
{
for(int i=2; i< X; i++)
{
if(X % i == 0){
X++;
continue;
}
}
System.out.println(X);
X++;
C++;
}
An optimized version :
// cache already found primes
final List<Integer> primes = new ArrayList<>();
/**
* Find {#code count} prime numbers starting at {#code start} inclusive
*/
public void findPrimes(int start, int count) {
for (int i = 2; count > 0; i++) {
if (isPrime(i) && i >= start) {
System.out.println(i);
count--;
}
}
}
private boolean isPrime(final int i) {
int sqrt = (int)Math.sqrt(i);
for (int prime : primes) {
if (i % prime == 0) {
return false;
}
if (prime > sqrt) {
break;
}
}
primes.add(i);
return true;
}
We really need to check for divisors only up to sqrt.
We really need to find only prime divisors since any number can be written as a product of prime numbers.
solution
#include <iostream>
using namespace std;
int main() {
int i, n;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> n;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
{
isPrime = false;
}
else
{
//algorithm to check for prime numbers
for (i = 2; i <= n / 2; ++i)
{
if (n % i == 0)
{
isPrime = false;
break;
}
}
}
if (isPrime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";
return 0;
}

How to factor a number and determine whether its a prime number

So i have this problem where when i factor a number, lets say 15, i have to display this: 15=3x5 but instead what i get is 3x5x5 and i have no clue of how to make it that so it only displays 3x5. And then another problem i have is to find whether the number i inputted is a prime number or not. Any way of fixing this? I just need that and the other stuff im gonna edit after that.
public class PrimeFactor
{
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
int a;
int d;
int remainder=0;
int count=2;
int c=0;
String s;
System.out.println("Enter an integer to be factored:");
a=input.nextInt();
s="";
d=a;
while(a>1)
{
if(a>1)
{
s="";
while(a>1)
{
remainder=a%count;
if (!(remainder>0))
while(remainder==0)
{
remainder=a%count;
if (remainder==0)
{
a=a/count;
c=c+1;
s=s+count+"x";
if (a==1)
s=s+count;
}
else
count++;
}
else
count++;
}
if (a%count==0)
{
System.out.println(d +"=" + s);
System.out.println(d+" is a prime number.");
}
else
System.out.println(d +"=" + s);
}
// TODO code application logic here
}
}
}
This determines if the number is prime or not the quickest way. Another method would be to use a for loop to determine the number of factors for the number and then say it's prime if it has more than two factors.
int num; // is the number being tested for if it's prime.
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) // only have to test until the square root of the number
{
if (num%i == 0) // if the number is divisible by anything from 2 - the square root of the number
{
isPrime = false; // it is not prime
break; // break out of the loop because it's not prime and no more testing needed
}
}
if (isPrime)
{
System.out.println(num + " is a prime number.");
}
else
{
System.out.println(num + " is a composite number.");
}
You are not constructing the factorization string quite right:
When you find that 3 divides a=15 you set s to 3x and set a to the quotient, so a=5
When you find that 5 divides a=5 you append 5x to s, so now s is 3x5x. Then you set a to the quotient, which is 1. Since the quotient is now 1, you append 5 again, so now you get 3x5x5.
What you'll want to do is append only 5 when a=1, not 5x5. You have to change this:
s=s+count+"x";
if (a==1)
s=s+count;
to this:
if (a==1) {
s=s+count;
} else {
s=s+count+"x";
}
How about trying like this:-
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("Number is a prime");
else
System.out.println("Number is not a prime");
break;
}
}
These are quite straight-forward methods you can use to factor a number and determine if it is a prime number:
public static int oneFactor(int i) {
for (int j = 2; j < i; j++) {
if (i % j == 0)
return j;
}
return -1;
}
public static Integer[] primeFactors(int i) {
List<Integer> factors = new ArrayList<Integer>();
boolean cont = true;
while (cont) {
int f = oneFactor(i);
if (i > 1 && f != -1) {
i /= f;
factors.add(f);
} else
factors.add(i);
if (f == -1)
cont = false;
}
return factors.toArray(new Integer[factors.size()]);
}
public static boolean isPrime(int i) {
if (i == 2 || i == 3)
return true;
if (i < 2 || i % 2 == 0)
return false;
for (int j = 3, end = (int) Math.sqrt(i); j <= end; j += 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
I am sure one can use faster algorithms, but those would be at the cost of simplicity, and it doesn't seem like you need high speed methods.
They all operate on ints, but its easy to change them to work with longs.
If you have any questions, feel free to ask!
You want to write a loop which loops through numbers 1 to (Inputted Number). And if you found a factor, you print it and divide the input by the factor. (And test if it can be divided again by the same number), else then skip to the next number.
Keep doing this until your input divides down to 1.
This program will break the number down to prime factors:
public class Factor {
public static void main() {
//Declares Variables
int factor = 15;
int i = 2;
System.out.println("Listing Factors:\n");
while (factor>1) {
//Tests if 'i' is a factor of 'factor'
if (factor%i == 0) {
//Prints out and divides factor
System.out.println(i);
factor = factor/i;
} else {
//Skips to next Number
i++;
}
}
}
}
Output:
Listing Factors:
3
5

Categories