count the number of each prime factor of a number - java

I want to count the number of each prime factor of an integer then print the highest number of counts. e.g. 720 = 2^4 * 3^2 * 5^1. so I want to print Maximum Number of Time occurrence = 4 and the number is 2. I try to use Integer.max(), but that didn't work.
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
int num;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
num = in.nextInt();
TreeMap<Integer, Integer> factors = new TreeMap<>();
for (int i =2; i < num; i++){
int count = 0;
while (num%i == 0){
System.out.println(i + " ");
num = num/i;
count ++;
}
if (count > 0){
factors.put(i, count);
}
}
if (num > 2){
System.out.println(num + " ");
factors.put(num, 1);
}
System.out.println( "-------------" );
for( Integer factor : factors.keySet() ){
System.out.println( factor + "^" + factors.get( factor ) );
}
}
}

If you just want the prime which occurs most then you can just check after each prime has been tested. For this, a map is not really necessary. Note that multiple primes may occur the same number of times. If there is a tie, this only saves the first one encountered.
int num;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
num = in.nextInt();
int primeFactor = 0;
int count = 0;
int maxCount = 0;
int inc = 1; // initial increment.
int i = 2; // intitial prime
while (num > 1) {
count = 0;
while (num%i == 0) {
num = num/i;
count++;
}
// here check current count against maxCount and
// alter if required.
if (count > maxCount) {
maxCount = count;
primeFactor = i;
}
if (count > 0) {
System.out.printf("Prime = %d, count = %d%n", i, count);
}
i+=inc; // bump by 1 to get 3 and then
inc = 2; // start incrementing by 2
}
// and print the results.
System.out.println("First highest occuring prime = " + primeFactor);
System.out.println("MaxCount = " + maxCount);

Related

How to quit scanner when input is negative?

This is the instructions.
Write a program that reads a sequence of input values and displays a bar chart of the values using asterisks. You may assume that all values are positive. First figure out the maximum value. That's value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.
This is what I came up so far. It's all good except I need to enter a letter instead of a negative number to quit scanning. I have tried (if( < 0) things) but those didn't work.
import java.util.Scanner;
public class BarChart1 {
public static void main(String [] args) {
int[] arr = new int[100];
int currentSize = 0;
System.out.println("Enter a sequence of positive integers. "
+ ("Enter a negative value to quit:"));
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0) {
break;
}
else {
arr[currentSize] = in.nextInt();
currentSize++;
}
}
//will find the max
double max = arr[0];
int y = 0;
for (int i = 1; i < arr.length; i++) {
y = i + 1;
if(max < arr[i]) {
max = arr[i];
//y = i + 1;
}
}
System.out.println("Max number is: " + max);
System.out.println("Number of digits = " + y);
System.out.println(Math.abs(-1));
double scale = 40/max;
System.out.println("Scale = " + scale);
for (int i = 0; i < y; i++) {
double h = scale * arr[i];
if (h != 0) {
for (int j = 1; j <= h; j ++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
This is the result.
1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************
I only need the asterisks. Everything else that is being printed is just for checking purposes.
You can try this:
while(in.hasNextInt()) {
int num =in.nextInt();
if(num <0){
break;
}
else{
arr[currentSize] = num;
currentSize++;
}
}

Why does the order of input to this LCM finding program change the output?

import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
class LCM {
static int GCF(int first, int second){
int FIR = first;
int SEC = second;
ArrayList<Integer> prime1 = new ArrayList<Integer>();
ArrayList<Integer> prime2 = new ArrayList<Integer>();
int n = 1;
// for the specific case of 2
while(true){
if(FIR % 2 == 0){
FIR /= 2;
prime1.add(2);
}
else break;
}
// for the rest of the prime numbers
for(int i = 3;;i = 2*n + 1){
if(FIR < i) break;
if(FIR == i) {
prime1.add(i);
break;
}
if(FIR % i == 0){
FIR /= i;
prime1.add(i);
}
++n;
}
// initialize n back to 1
n = 1;
// for the specific case of 2
while(true){
if(SEC % 2 == 0){
SEC /= 2;
prime2.add(2);
}
else break;
}
// for the rest of the prime numbers
for(int i = 3;; i = 2*n + 1){
if(SEC < i) break;
if(SEC == i){
prime2.add(i);
break;
}
if(SEC % i == 0){
SEC /= i;
prime2.add(i);
}
++n;
}
// Collect all common prime factors to calculate GCF
List<Integer> common = new ArrayList<Integer>(prime2);
common.retainAll(prime1);
int GCF = 1;
for(int i = 0; i < common.size(); i++){
GCF *= common.get(i);
}
return GCF;
}
// End of LCP function
static int lcp(int first, int second){
return (first / GCF(first, second)) * second;
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int first = 0;
int second = 0;
while(true){
System.out.print("Enter first number: ");
first = input.nextInt();
System.out.print("Enter second number: ");
second = input.nextInt();
System.out.print("LCM (" + first + ", " + second + ")" + " = ");
System.out.print(lcp(first, second) + "\n");
}
}
}
The code works perfectly when I give it input in one order but it give's the wrong output when I reverse the order of input. For example it outputs
LCM(12, 10) = 56
when I input the two numbers in the order 12 then 10. But it outputs
LCM(10, 12) = 24
when the input is reversed. I tried debugging the code but I couldn't see any obvious problem.
LCM of (10, 12) is 60, NOT 56
If you wish to calculate the LCM of two numbers entered by the user, here's a simpler version that calculates the LCM
class LCM {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int first = 0;
int second = 0;
while(true){
System.out.print("Enter first number: ");
first = input.nextInt();
System.out.print("Enter second number: ");
second = input.nextInt();
System.out.print("LCM ("+first + ","+second+") = " +lcp(first, second) + "\n");
}
}
public static int gcf(int first, int second) {
HashSet<Integer> firstFactors = new HashSet<>();
HashSet<Integer> secondFactors = new HashSet<>();
HashSet<Integer> commonFactors;
//factors of first number
for(int i=1; i<=first; i++) {
if(first%i == 0) {
firstFactors.add(i);
}
}
//factors of second number
for(int i=1; i<=second; i++) {
if(second%i == 0) {
secondFactors.add(i);
}
}
commonFactors = new HashSet<>(firstFactors);
commonFactors.retainAll(secondFactors);
return Collections.max(commonFactors);
}
static int lcp(int first, int second){
return (first / gcf(first, second)) * second;
}
}

For loop with summing feature

I'm trying to write a for loop that will take a user input, regardless if it is positive or negative, display the input numbers and then display the sum of the numbers. I can get as far as displaying the numbers, but I am having a hard time getting the summing right.
import java.util.Scanner;
public class DisplayandSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Variable declaration
int size;
int Num1;
int count = 0; //LCV
int sum = 0; //Sum of inputs
String newNum; // Declared string for user input
System.out.println("Please enter an integers and press enter.");
newNum = input.next();
Num1 = Integer.parseInt(newNum);
size = newNum.length();
System.out.print("These are your numbers: ");
if (Num1 > 0) //If number is positive
{
for (count = 0; count <= (size - 1); count++) {
System.out.print(newNum.charAt(count) + "");
}
} else if (Num1 < 0) // If number is negative
{
System.out.print("-");
for (Num1 = 1; Num1 <= (size - 1); count++) {
System.out.print(newNum.charAt(count) + "");
}
}
if (Num1 > 0) //If positive sum
{
for (count = 0; count < (size - 1); count++) {
sum = sum + count;
}
} else if (Num1 < 0) // If negative sum
{
for (Num1 = size; Num1 > 2; Num1--) {
Num1 = Math.abs(Num1);
}
sum = sum + Num1 % 10;
Num1 = Num1 / 10;
}
sum = sum + (0 - Num1);
System.out.println("\nand the sum of your digits is: " + sum);
}
}
When you say "sum of the numbers", I assume you actually mean "sum of the digits"?
Your code is more complicated than it needs to be.
// Variable declaration
int sum = 0; //Sum of inputs
String newNum; // Declared string for user input
System.out.println("Please enter an integer and press enter.");
newNum = input.next();
size = newNum.length();
System.out.print("These are your numbers: ");
for (count = 0; count < size; count++)
{
char ch = newNum.charAt(count);
if (Character.isDigit(ch) {
System.out.print(ch);
sum += (ch - '0');
}
}
System.out.println("\nand the sum of your digits is: " + sum);

While loop even count

my problem is the following. If I input number 2, the code counts it as an odd number.
Remainder for 2 / 2 = 0 so the error doesn't make sense.
Below is the program:
import java.util.Scanner;
public class Ohjelma {
public static void main(String[] args) {
// Tänne voit kirjoittaa ohjelmakoodia. Ohjelmasi voit ajaa
// valitsemalla menusta Run->Run File tai painamalla Shift+F6
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int number = Integer.parseInt(reader.nextLine());
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
while (number != -1) {
System.out.println("Type numbers: ");
sum = sum + number;
number = Integer.parseInt(reader.nextLine());
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + many);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
The main problem is that for the critical part of your program it largely ignores the first input, apart from adding it to the running sum. You want to recast it like this:
Scanner reader = new Scanner(System.in);
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;
do {
System.out.println("Type numbers: ");
number = Integer.parseInt(reader.nextLine());
if (number == -1)
break;
sum = sum + number;
many++;
average = (double)sum / many;
if (number%2 == 0) {
even++;
} else {
odd++;
}
} while (true);
This will certainly processes even and odd numbers correctly.
Your code reads the second line of input into number before it checks whether number is odd ... and -1 is odd.

Combine for and while loop (Java)

I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}

Categories

Resources