I am trying to print last three prime numbers less than 100. If I print less than 10 prime number it is working correctly. But when I try to print less than 100 it is not working correctly. I don't know why. Can you tell me an efficient way to print last three numbers?
int[] a = new int[100];
int flag=0,c=0,i=2,j=2;
int n=10;
while(i <= n)
{
flag=0;
while(j<=i/2)
{
if(i%j==0)
{
flag=1;
break;
}
j++;
}
if(flag==0)
{
a[c]=i;
c++;
}
i++;
}
for(i=0;i<c;i++)
{
c--;
System.out.print(a[c]+" ");
}
First you have to re-init the variables j and flag.
while(i <= n) {
//...
if(flag==0) {
a[c]=i;
c++;
}
i++;
j = 2;
}
You can show the last three prime like this
for(i = c-1; i >= c-3; i--) {
System.out.print(a[c]+" ");
}
Or you can use this code
int numToShow = 3, n = 100;
boolean isPrime = true;
while(n > 1 && numToShow > 0) {
for (int j = 2; j <= (int) Math.sqrt(n) && isPrime; j++) {
if(n % j == 0) {
isPrime = false;
}
}
if (isPrime) {
System.out.print(n + " ");
numToShow--;
}
isPrime = true;
n--;
}
Related
What I need it to do is print all of the prime numbers starting at 1 and ending at the input, if the input is also a prime number. Here's my code now:
static void primeNumbers(int n) {
boolean isPrime;
System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime = prime++) {
if (n % prime == 0) {
isPrime = false;
}
if(isPrime == true){
System.out.println(prime);
}
}
}
My teacher said that I need to make a nested for loop, but I just don't know what to put in it. I'm also getting an error saying that my last use of isPrime hasn't been initialized.
You need to actually check for primality, and not just see if the number is a factor of n:
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
for (int k = 3; k * k <= n; k += 2) {
if (n % k == 0) {
return false;
}
}
return true;
}
static void primeNumber(int n) {
System.out.println("All the prime numbers up to " + n + " are -->");
for (int num = 2; num < n; num ++) {
if (isPrime(num)) {
System.out.println(num);
}
}
}
You will need to do something like this for your program to work.
static void primeNumbers(int n) {
boolean isPrime = true;
System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime++) {
if (n % prime == 0) {
isPrime = false;
}else{
isPrime = true;
}
if(isPrime){
System.out.println(prime);
}
}
}
It is necessary to initialize isPrime.
And, Eratosthenes' s sieve is famous algorithm for get prime numbers.
I think the URL below will help you.
https://www.geeksforgeeks.org/java-program-for-sieve-of-eratosthenes/
here is one of the solutions
public static void main(String[] args) {
int n = 23;
boolean[] isPrime = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
isPrime[i] = true;
}
for (int i = 2; i <= n / i; i++) {
if (isPrime[i]) {
for (int j = i; j <= n / i; j++) {
isPrime[i * j] = false;
}
}
}
for (int i = 1; i <= n; i++) {
if (isPrime[i]) {
System.out.println(i);
}
}
}
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;
}
}
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);
}
}
}
in java what i am trying to do is have a user input a value greater than 0 and with that number they input list that amount of prime numbers starting from 2
so if the user inputs "3" the program will display 2,3,5
if the user inputs "5" the program will display 2,3,5,7,11
and so on
the problem is I cant figure out how to have the user input do this correctly, i either end up with the numbers repeating however many times or the list ending at the user input, any help would be apreciated
import java.util.Scanner;
public class Primes
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int n = console.nextInt();
if(n<=0)
{
return;
}
else
{
for(int i=2; i < 100; i++)
{
boolean isPrime = true;
for(int j=2; j < i; j++)
{
if(i%j == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
System.out.println(i);
}
}
}
}
}
Keep a count of how many primes have been found by changing your for loop to stop when you've found enough primes and performing primesFound++ when a prime is found:
for (int i = 2, primesFound = 0; primesFound < n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
System.out.println(i);
primesFound++;
}
}
I rather have code that is refactored, each method is doing one thing, it makes it much easier to read, debug and maintain.
All we need to do is separate the logic that checks if a number is prime from the logic that goes over the numbers until n prime numbers are found:
public static void main(String[] args) {
printNPrimes(5);
}
static private boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static private void printNPrimes(int n) {
int i = 2;
while (n > 0) {
if (isPrime(i)) {
System.out.println(i + " is Prime");
n--;
}
i++;
}
}
//prime
int i,j;
Set<Integer> primeNums = new HashSet<>();
Set<Integer> notPrimeNums = new HashSet<>();
Stack<Integer> stack = new Stack<>();
for(i=1; i<fiboList.size(); i++) {
for(j=i+1; j<fiboList.size(); j++) {
if( i % j == 0 ) {
notPrimeNums.add(fiboList.get(i));
}else {
primeNums.add(fiboList.get(i));
}
}
}
stack.addAll(primeNums);
Collections.sort(stack);
System.out.println("Prime numbers:"+" "+stack);
}
static void primeNumbers(int n)
{
System.out.println("All the prime numbers up to "+n+" are -->\n");
boolean isPrime = true;
for(int i = 2; i < n; i++)
{
for (int j = 1; j < i; j++)
{
if(i % j == 1)
{
isPrime = true;
System.out.print(j);
}
if(i % j == 0)
{
isPrime = false;
System.out.print(" ");
}
}
}
}
In this code I am trying to list all the prime numbers up to 'n' which is the number the user inputs. I am confused as to how to fix this to produce all of the prime numbers up to n.
You want to test if i is dividable by any number in the range of [2..i-1] and if it is, then it is not a prime number. Your j-loop starts at 1, that is the first error.
Knowing when a number is dividable by another is tested like this: if (i % j == 0) { (if the division remainder is zero) where in your code you test for equality with 1 instead.
Third thing is that you make your decision in the first iteration (when j is 1) and always print something in your inner loop. You need to take the logic out of the inner loop. Only if i is not dividable by any of the js then it is prime.
Here is a modified version of your code:
static void primeNumbers(int n) {
System.out.println("All the prime numbers up to "+n+" are -->\n");
for (int i = 2; i < n; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if(i % j != 0) {
isPrime = false;
}
}
if (isPrime) {
System.out.print(i, " ");
}
}
}
if (i % j == 0) {
isPrime = false;
System.out.print(" ");
}
This if statement is always true for any i because j starts at 1. As a result, you print a space for every number < n and >= 2
Also, isPrime may be an unnecessary variable.
Your algorithm, although slow, seems to be correct on most parts except for the fact that you are not handling the boundary conditions well. E.g. 2 is a prime number, you are running iterations only till n-1, you are not reseting the isPrime flag for every number, and a few small things. Here's a revised working version. Try to compare it with yours and understand where you didn't get it right.
int n = 10;
System.out.println("All the prime numbers up to "+n+" are -->\n");
boolean isPrime = true;
for(int i = 2; i <= n; i++)
{
for (int j = 2; j < i; j++)
{
if(i % j == 0)
{
isPrime = false;
break;
}
}
if(isPrime) {
System.out.println(i);
}
isPrime = true;
}
Don't re-set isPrime to true in your second for loop, as soon as the number is not prime once, we know it is not prime forever. Just set it to true once every iteration of the outer loop, and do your final "Is prime" check outside.
static void isPrime(int n)
{
System.out.println("All the prime numbers up to "+n+" are -->\n");
for(int i = 2; i <= n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if(i % j == 0)
{
isPrime = false;
System.out.println(i + " is not prime because " + i + " is divisible by " + j );
break;
}
}
if (isPrime){
System.out.println(i + " is prime.");
}
}
}
I've added a couple prints to this code so that you can see why each part of the logic is doing what it does -- compare it to your code so that you can understand why yours doesn't actually search for primes.
I think is a logical problem in your script.
You should count with a loop all the number from 2 to n-1 which are = to 0 with a test
n%i = 0
If the counter = 0 then no divider then prime number