java for loop factors program - java

Hi I have to make a program(java) on which you input a number and it outputs the number of factors it has(EX: 4 ---> 3)
Code:
package Class;
import java.util.Scanner;
public class Profgrams {
public static void main(String[] args) {
System.out.println("Enter the number;");
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
for(int i=1, f=0; i <= n; i++){
if(n % i == 0){
f++;
}
System.out.println(f);
}
}
}
Thanks for help.

Declare and initialize f before the loop, and then print the result after the loop terminates. That way printing will not occur at each iteration of the loop.
int f = 0;
// ...
System.out.println(f);

Related

Prevent trailing character when printing values in a loop [duplicate]

This question already has answers here:
Printing with delimiter only between values
(3 answers)
Closed 2 years ago.
I was tasked to do a looping problem for Java, but I'm currently having a problem on how to display a factorial of a number. For example, 1x2x3x4x5 = 120.
I'm almost there, but I can't seem to figure out how to, or is there any possible way to display the factorial of a number because there is always an additional "x" at the end of the 5.
Here is my code:
import java.util.*;
public class trylangpo2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
int j;
for (j =1; j <=1 ; j++){
System.out.print("*");
}
}
}
}
Example output:
1x2x3x4x5x
Your loop for (j =1; j <=1 ; j++) can be removed. It only loops once so, just write System.out.print("*"). No loop required
Then if you think about it, you want to print the number and the * all the time, except when it is the last number (fctr)
So write it that way:
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
if(i<fctr) {
System.out.print("*");
}
}
Try to add a condition if it’s not at the end of the loop. Then add start and if it’s the end, then just print the number:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
for (int i = 1; i <= fctr; i++) {
if (i < fctr) {
System.out.print(i + " * ");
} else {
System.out.print(i);
}
}
}
I always use a construct like
String sep="";
for (...) {
System.out.print(sep);
System.out.print(payload);
sep="x";
}
You need to make the printing of ***** condition. Don't print ***** if i == fctr. And you don't need that additional loop of j. As below :
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
// IntStream.range(1, fctr).
long factorial = 1;
for (int i = 1; i <= fctr; i++) {
factorial = factorial * i;
if (i == fctr) {
System.out.print(i);
} else {
System.out.print(i + "*");
}
}
System.out.print("=" + factorial);
}

N prime numbers in java

So I've written this code in java which should output numbers on the screen from 1 to n(given by the user) and it should write "-prime" near the ones that are prime.
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++)
for(j=2;j<=n/2;j++)
{
if(i%j==0)
System.out.println(i);
else System.out.println(i +"-prime");
}}
}
If I input 6 for example i get :
Dati n: 6
1-prime
1-prime
2
2-prime
3-prime
3
4
4-prime
5-prime
5-prime
6
6
I'm new to this, and i'm really struggling with my algorithmic, could you tell me how should i change my program so it outputs correct values, and explain to me what i did wrong ? Thank you
UPDATE:
I've done it, thank you everyone for helping me out : this is the outcome:
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
boolean gasit = false;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++) {
gasit=false;
for(j=2;j*j<=i;j++)
{
if(i%j==0) gasit=true;}
if(!gasit) {System.out.println(i+"-prime");}
else {
System.out.println(i);}
}
}
}
You print something on every iteration of the inner loop.
Instead, you should print something after all iterations have completed, e.g.
boolean found = false;
for(j=2;j<=n/2;j++) {
if(i%j==0) found = true;
}
if (!found) {
System.out.println(i + "-prime");
} else {
System.out.println(i);
}
Additionally, you shouldn't be going up to n/2: you perhaps mean i/2 (a number doesn't have any factors greater than itself); but you can make it even tighter, since you don't have to check for factors greater than sqrt(i). Or, stated another way, that j * j <= i.
So you can make your loop declaration:
for(j=2; j*j<=i; j++) {
The problem is that the second loop goes until n/2, it should go until i/2 to check if i is prime. A more optimzed version of the primality check algorithm goes until sqrt(i), as suggested in comments.
The next issue is that you are concluding, in a false way, that if in the first case if(i%j==0) you say not prime, otherwise you say it is prime, which is not true necessairly. You should iterate the whole interval of values between [2:i/2] to conclude that i is prime.

Using arrays to store primes

Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}

NoSuchElementException with Java.Util.Scanner with array

I m very new to java and don't know why I'm getting this error when I run below program
program : this program basically read no of input N in first line and then scan each number and store it in array arr and display it.
range of N is : 0<N<10^6
input numbers can be long so that I used long array in the program.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
long no = sc.nextLong();
if(no > 1000000 || no < 1)
System.exit(0);
long arr[] = new long [(int)no];
for(int i=0;i<(int)no;i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}
}
}
input values : here you find input values
output :
Runtime Errors
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextLong(Scanner.java:2265)
at java.util.Scanner.nextLong(Scanner.java:2225)
at Solution.main(Solution.java:23)
rest of output is here
You are repeatedly calling nextLong(), but not testing to see if there is a next long:
for(int i=0;i<(int)no;i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}
You need do something like this:
for(int i=0;i<(int)no && sc.hasNextLong();i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}
It's supposed to be something like this:
import java.util.Scanner;
import java.io.InputStream;
class Solution {
public static void main(String... args) {
InputStream in;
// initialize in
Scanner scanner = new Scanner(in);
int[] numbers;
// You don't need to store long values because int values fall within 0 and 10^6
try {
numbers = new int[(scanner.hasNextInt()? scanner.nextInt(): 0)];
} catch(NegativeArraySizeException nase) {
numbers = new int[0];
}
// we store the limits in variables so that your system doesn't create them repeatedly in each iteration
for(int i = 0, number, LOW = 0, HIGH = 1000000; scanner.hasNextInt() && i < numbers.length;) {
number = scanner.nextInt();
if(number > LOW && number < HIGH) {
numbers[i] = number;
// go to next index only if we have a number
i++;
}
}
}
}

getting input from stdin

I want to get input from stdin in the for of
3
10 20 30
the first number is the amount of numbers in the second line. Here's what I got, but it is stuck in the while loop... so I believe. I ran in debug mode and the array is not getting assign any values...
import java.util.*;
public class Tester {
public static void main (String[] args)
{
int testNum;
int[] testCases;
Scanner in = new Scanner(System.in);
System.out.println("Enter test number");
testNum = in.nextInt();
testCases = new int[testNum];
int i = 0;
while(in.hasNextInt()) {
testCases[i] = in.nextInt();
i++;
}
for(Integer t : testCases) {
if(t != null)
System.out.println(t.toString());
}
}
}
It has to do with the condition.
in.hasNextInt()
It lets you keep looping and then after three iterations 'i' value equals to 4 and testCases[4] throws ArrayIndexOutOfBoundException.
The Solution to do this could be
for (int i = 0; i < testNum; i++) {
*//do something*
}
Update your while to read only desired numbers as below:
while(i < testNum && in.hasNextInt()) {
The additional condition && i < testNum added in while will stop reading the numbers once your have read the numbers equivalent to your array size, otherwise it will go indefininte and you will get ArrayIndexOutOfBoundException when number array testCases is full i.e. you are done reading with testNum numbers.

Categories