how to output prime numbers in a table - java

I am working on a project that take in a starting number and a number of primes then outputs a table with each prime number after your starting number until it reaches your number of primes. I wrote a program to find the prime numbers but im having trouble getting the output to format in a table. I know i need to use nested for loops to build the table but im not sure how to go about starting that. Here is my code so far:
class Tester2{
public static void main(String[] args){
int number = 750000; //starting number
int nofn = 12; //number of primes to find
int primecount = 0;
while(primecount < nofn){
if(isPrime(number)){
primecount ++;
System.out.println(primecount + " " +number);
}
number++;
}
}
//determins if num is prime
private static boolean isPrime(int num){
int divisor = 2;
boolean itIsPrime;
while(num % divisor != 0){
divisor++;
}
if(divisor == num)
itIsPrime = true;
else
itIsPrime = false;
return itIsPrime;
}
}
Currently my code returns
1 750019
2 750037
3 750059
4 750077
5 750083
6 750097
7 750119
8 750121
9 750131
10 750133
11 750137
12 750151
and I am looking for it to return
Row #: 1--> 750019 750037 750059 750077 750083 750097 750119 750121 750131 750133
Row #: 2--> 750137 750151

Here you go. I also improved your isPrime method to loop until sqrt(num) instead of num, so it should be much faster now:
public class Test {
public static void main(String[] args) {
int number = 750000; // starting number
int nofn = 100; // number of primes to find
int primecount = 0;
int row = 0, col = 0;
while (primecount < nofn) {
if (isPrime(number)) {
primecount++;
if (col++ == 0)
System.out.print(String.format("%3d-->", ++row));
System.out.print(String.format(" %6d", number));
if (col == 10) {
System.out.println();
col = 0;
}
}
number++;
}
}
private static boolean isPrime(int num) {
final int last = (int) Math.sqrt(num);
for (int divisor = 2; divisor <= last; ++divisor) {
if (num % divisor == 0)
return false;
}
return true;
}
}
Output:
1--> 750019 750037 750059 750077 750083 750097 750119 750121 750131 750133
2--> 750137 750151 750157 750161 750163 750173 750179 750203 750209 750223
3--> 750229 750287 750311 750313 750353 750383 750401 750413 750419 750437
4--> 750457 750473 750487 750509 750517 750521 750553 750571 750599 750613
5--> 750641 750653 750661 750667 750679 750691 750707 750713 750719 750721
6--> 750749 750769 750787 750791 750797 750803 750809 750817 750829 750853
7--> 750857 750863 750917 750929 750943 750961 750977 750983 751001 751007
8--> 751021 751027 751057 751061 751087 751103 751123 751133 751139 751141
9--> 751147 751151 751181 751183 751189 751193 751199 751207 751217 751237
10--> 751259 751273 751277 751291 751297 751301 751307 751319 751321 751327

You are using System.out.println every time you need to print. This prints a new line every time a prime is found. What you need to do is use the function System.out.print to print your information. Then, after a 10 primes have been found, implement the function System.out.println.
if(isPrime(number)){
primecount ++;
if(primecount%10==0)
System.out.println(number+" ");
else
System.out.print(number+" ");
}

Not clear what you mean by table. If you just want to print 10 prime numbers on 1 row you can do:
while(primecount < nofn){
if(isPrime(number)){
primecount ++;
System.out.print(primecount + " " +number);
if (primecount%10==0)
System.out.println();
}
number++;
}

To print the row number this should be the code.
public static void main(String[] args) {
int number = 750000; //starting number
int nofn = 12; //number of primes to find
int primecount = 0;
int rowCount = 1;
System.out.print(rowCount + "--> ");
while (primecount < nofn) {
if (isPrime(number)) {
primecount++;
System.out.print(number + " ");
if (primecount % 10 == 0) {
System.out.println();
rowCount++;
System.out.print(rowCount + "--> ");
}
}
number++;
}
}

I mean if you just want to skip it after like 8 entries, you have to do a nested loop how you said.
Not a very good solution, since it could get stuck in the while loop and its not beautiful code at all, but I guess it could work somehow like this:
Edited
int rowCount = 0;
while(primecount < nofn){
if(isPrime(number)){
if(primeCount% 10 == 0) {
rowCount++;
System.out.println("Row #: " + rowCount + "-->");
}
primecount ++;
System.out.print(" " +number); // print not printl
}
number++;
}

Related

How can i get a false value if the inputted number isn't a happy one?

*hi there here is my answer for this challenge :
Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
my code works and outputs a true value only if the number is a happy one*
public class Main {
public static void main(String[] args) {
System.out.println(isHappy(12));
}
public static boolean isHappy(int number) {
while (number != 1 ) {
number = SumOfintegers(number); //to keep looping until It find sum=1
}
return true ;
}
public static int SumOfintegers(int number){
int sum =0;
int news = 0;
while (number > 0) {
int num = number % 10;
number /= 10;
news = num * num;
sum = sum + news;
}
return sum;
}
}
so I have solved this "happy number" problem once and this is my code using recursion with explanation:
public static void main(String[] args) {
System.out.println(nextHappyNum(0));
}
//method to find next happy number
static int nextHappyNum(int num){
int x =num+1;
if(isHappy(x) == true){ //base case where the next number is happy number
return x;
} else{
return nextHappyNum(num+1); //recursively call the method to check
}
}
//method to check if number is happy or not
static boolean isHappy(int num){
while(num != 1 && num != 4){
num = calculateHappy(num); //this loop will call the checkHappy() method until it reach 1 or 4
}
if(num == 1){ //if result is 1 -> happy number
return true;
} else if(num == 4 ){ //final result is 4 -> not happy number
return false;
} else{
return false;
}
}
//method to calculate the sum of number digits
static int calculateHappy(int num){
int sum = 0;
int rem = 0;
//create while loop to calculate the digit number, remainder of modulus 10 is the second digit
//first digit is = the number/10 and the remainder of that int
while(num != 0){
rem = num%10; //calculating the remainder
sum += (rem*rem); //calculate the square root of remainder and add it to the sum
num = num/10; //divide the number by 10 - due to this data type is int, so the first digit will be taken
}
return sum;
}

I need some help diagnosing the problem with this code

I'm having trouble with some code. This code's purpose is just to take user-inputted numbers, append them to a string, and create a histogram representing the amount of numbers in each 5 number range from 1 to 50. Ex.
1 - 5: ***
6 - 10: ********
11 - 15: *
etc.
Here is the code:
public class Ch10Ex4 {
public static int number;
public static ArrayList<Integer> numbers = new ArrayList<>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
getNums(1, 50);
}
histogram(1, 50, 5);
System.out.println();
}
public static void getNums(int low_num, int high_num) {
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a number between " + low_num +
" and " + high_num + ": ");
number = sc.nextInt();
} while (number < 1 || number > 50);
System.out.println(number + " has been added sucsessfully.");
numbers.add(number);
}
public static void histogram(int low, int high, int range) {
int temp_low = low;
int temp_high = low + (range - 1);
for (int i = 0; i < high / range; i++) {
System.out.print("\n" + temp_low + " - " + temp_high + ": ");
for (int arr:numbers) {
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
}
temp_low += range;
temp_high += range;
}
}
}
I had a previous version of this code where I would call histogram() with two parameters. These would be the lowest number and the highest number like usual but no int range parameter. And I didn't have the outermost for-loop. I would have to call histogram 10 times ex.
histogram(1, 5);
histogram(6, 10);
histogram(11, 15);
etc.
Basically, I would call it for every set of five numbers. It worked but it was super inefficient and not very reusable. The problem is that when I run this code (entering numbers 1- 10), I get this:
1 - 5: **********
6 - 10: *****
11 - 15:
16 - 20:
etc.
The first set of five outputs an asterix for every number in the array.
Sorry for the incredibly long post. Any help is much appreciated and thank you in advance.
The bug is that you are using i in this if-statement.
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
Switch it to arr and you should be good.

Print odd numbers in a descending order

The program needs to take an odd number and output it in a descending order
For example: if the input is 11 the output needs to be 11 , 9 , 7 , 5 , 3, 1.
I tried using a for loop but I can only seem to get it to work with even numbers not odd numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
for (int i = number - 1; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
}
The output is the number in descending order but as even only. If I add a 1 into the descend variable the numbers would seem to descend in an odd manner but its not ideal.
This line returns true if the number is even:
if (i % 2 == 0) {
If you want to know when the number is odd:
if (i % 2 != 0) {
Also, why are you starting your count at 1 less than the input value:
int i = number - 1;
I think you want to do this:
for (int i = number; i > 0; i--) { // tests for numbers starting at the input and stopping when i == 0
Just replace (i%2==0) to (i%2==1)
Asking if the number % 2 is equal to zero is basically asking if the number is even, so what you really have to do is ask if the number % 2 is not equal to zero, or equal to 1
if (i % 2 != 0) {
int descend = i;
System.out.println(descend + " ");
}
Also, there's no need to subtract 1 from the user input so your for loop can be written like this
for (int i = number; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an an odd number: ");
int number = input.nextInt();
while(number%2==0){
System.out.print("Number must be odd number:" +
"(Ex:1, 3,5)\nTry again: ");
number=input.nextInt();
}
for (int i = number; i >= 0; i--) {
if(number%2!=0){
System.out.println(number);}
number-=1;
}
}

Trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20

I'm trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. We are given that 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. My find() finds the number starting from 2520 that is divisible by all numbers from 1-20 but is returning 2520 for some reason. I cannot find what's wrong about my find()?
public class Solution {
public ArrayList<Integer> list = new ArrayList<Integer>();
// creating a list of integers from 1 to 20
public ArrayList<Integer> addtolist() {
for (int i = 1; i <= 20; i++) {
list.add(i);
}
return list;
}
// finds the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20
public int find() {
int num = 2520;
while(true) {
for(int i: list) {
if(num % i == 0) {
return num;
}
else {
num = num + 1;
}
}
}
}
public static void main(String[] args) {
Solution sol = new Solution();
sol.addtolist();
System.out.println(sol.find());//2520
}
}
Your find function returns num if any i in list divides it. It should only return num if every i in num is a divisor.
Although it has to be said that this is far from the most efficient solution to the problem.
You return from the for loop when (num % i == 0), given that i starts at 1 this always true. Instead you need to wait until the end to return:
public int find() {
int num = 2520;
while(true) {
boolean allDivisible = true;
for(int i: list) {
if(num % i != 0) {
allDivisible = false;
break;
}
}
if (allDivisible) {
return num;
else {
num = num + 1;
}
}
}
In your code:
for(int i: list) {
if(num % i == 0) {
return num; // Returns immediately.
}
else {
num = num + 1;
}
}
you return as soon as you find some number in the list that has a match. What you want to do is only return when you have found a value that matches all in the list.
Nice question!
long answer = LongStream.iterate(1, n -> n + 1)
.filter(n -> IntStream.rangeClosed(1, 20).allMatch(f -> n % f == 0))
.findFirst().getAsLong();
Answer is 232792560
There are obviously plenty of shortcuts using math (e.g. only looking at even numbers, ignoring numbers in 1 to 20 that are factors of other numbers in that range).

How does this prime number test in Java work?

The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.
public static void main(String[] args)
{
int j = 2;
int result = 0;
int number = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = reader.nextInt();
while (j <= number / 2)
{
if (number % j == 0)
{
result = 1;
}
j++;
}
if (result == 1)
{
System.out.println("Number: " + number + " is Not Prime.");
}
else
{
System.out.println("Number: " + number + " is Prime. ");
}
}
Overall theory
The condition if (number % j == 0) asks if number is exactly divisible by j
The definition of a prime is
a number divisible by only itself and 1
so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.
Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.
Specific sections
While loop
This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6
int j = 2;
.....
while (j <= number / 2)
{
........
j++;
}
If statement
This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.
......
if (number % j == 0)
{
result = 1;
}
.....
Further improvements
Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).
It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.
I've tried to comment each line to explain the processes going on, hope it helps!
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
It works by iterating over all number between 2 and half of the number entered (since any number greater than the input/2 (but less than the input) would yield a fraction). If the number input divided by j yields a 0 remainder (if (number % j == 0)) then the number input is divisible by a number other than 1 or itself. In this case result is set to 1 and the number is not a prime number.
Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
Miller–Rabin primality algorithm is used to check primality in this method.
import java.math.BigInteger;
public class TestPrime {
public static void main(String[] args) {
int number = 83;
boolean isPrime = testPrime(number);
System.out.println(number + " is prime : " + isPrime);
}
/**
* method to test primality
* #param number
* #return boolean
*/
private static boolean testPrime(int number) {
BigInteger bValue = BigInteger.valueOf(number);
/**
* isProbablePrime method used to check primality.
* */
boolean result = bValue.isProbablePrime(1);
return result;
}
}
Output: 83 is prime : true
For more information, see my blog.
Do try
public class PalindromePrime {
private static int g ,k ,n =0,i,m ;
static String b ="";
private static Scanner scanner = new Scanner( System.in );
public static void main(String [] args) throws IOException {
System.out.print(" Please Inter Data : ");
g = scanner.nextInt();
System.out.print(" Please Inter Data 2 : ");
m = scanner.nextInt();
count(g,m);
}
//
//********************************************************************************
private static int count(int L, int R)
for( i= L ; i<= R ;i++){
int count = 0 ;
for( n = i ; n >=1 ;n -- ){
if(i%n==0){
count = count + 1 ;
}
}
if(count == 2)
{
b = b +i + "" ;
}
}
System.out.print(" Data : ");
System.out.print(" Data : \n " +b );
return R;
}
}

Categories