package Testing;
import java.util.Scanner;
public class test {
public static void main (String[] args){
Scanner scan1 = new Scanner(System.in);
System.out.print("Input positive integer: ");
int n = scan1.nextInt();
for (int i = 2; i < Math.sqrt(n); i++){
if (n % i == 0){
System.out.print(n/i);
}
}
}
}
When I run this code it ends up printing the numbers 2510 whenever I input 50. What did I do wrong?
As was mentioned in the comments, you're very close, but you need to stop iterating after you find an answer. This can be done with the break keyword, which exits the innermost loop.
for (int i = 2; i < Math.sqrt(n); i++){
if (n % i == 0){
System.out.print(n/i);
break;
}
}
You have to stop when you find the first prime factor. And do not forget, that in your example Math.sqrt(n) is calculated every loop.
public static int getLargestFactor(int num) {
for (int i = 2, max = (int)Math.sqrt(num); i <= max; i++)
if (num % i == 0)
return num / i;
return num;
}
Related
I need to find all prime numbers between 2 and n, the user informs n. However, I cannot use "for", only "while", but I can't make the program works using "while". Can somebody help me?
This is the program I made with "for"
import java.util.Scanner;
class Main {
public static void main(String [] args) {
int i;
int cont;
int n;
System.out.print("Enter a number: ");
Scanner leia = new Scanner(System.in);
n = leia.nextInt();
System.out.println("The prime numbers from 2 to "+n+" are: ");
for(int j = 2; j <= n; j++) {
cont = 0;
for(i = 1;i <= j; i++) {
if(j % i == 0) {
cont++;
}
} if(cont == 2) {
System.out.print(j+" ");
}
}
}
}
Your for loop
for (int j = 2; j <= n; j++){
//Do whatever
}
can be easily re-written as a while loop
int j = 2;
while (j <= n){
//Do whatever
j++;
}
A for loop is basically a specialized while loop that lets you define a starting variable, a stop condition, and an increment value.
A basic while loop only has a stop condition, so in order to accomplish what a for loop does, you just need to define the starting variable j and the incremental j++
public static boolean isPrime(int n) {
if(n == 1) {
return false;
}
for(int i = 2; i <= (long) Math.sqrt(n); i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
public static void printPrimes(int endPoint) {
int i = 2;
System.out.printf("The prime numbers between 2 and %d are:%n", endPoint);
while(i <= endPoint) {
if(isPrime(i)) {
System.out.println(i);
}
i++;
}
}
This is my first submission here so please forgive me if this is formatted poorly.
Echoing what mmartinez04 said, the while loop functions very similarly to a for as far as iterating through a sequence of integers in this particular situation. The key aspect is ensuring that you are incrementing i in the body of the loop to prevent an endless loop.
I wrote the armstrong number question in java by myself(sorry if its silly, I'm new to programming).
The "result is supposed to give 1 value when i enter a coorect armstrong number but it gives 0,why?
Code-
import java.util.Scanner;
public class Exercise1_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int result = 0;
int i = 0;
int sum = 0;
while (n > 0) {
i = n % 10;
sum += i * i * i;
n = n / 10;
}
if (sum == n) {
System.out.print("1");
} else {
System.out.print("0");
}
n is changed in the while loop. After the while loop n == 0 (if n was entered as a non-negative number). This the only case where sum == n is true will be sum == 0. You need to introduce a temporary variable which is modified in the loop and keep n unchanged.
int temp = n;
while (temp > 0) {
int i = temp % 10;
sum += i * i * i;
temp /= 10;
}
N.B. result is not used, i not decalred inside the while loop
import java.util.Scanner;
public class PrimeN {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
while (a < b) {
for (int i = a; i <= b; i++) {
int count = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
count++;
}
} //count if equals 2 the prime numbers displayed
if (count == 2) {
System.out.println(i);
a++;
}
}
}
}
}
This is what my output looks like. I dont understand why last prime numbers are being repeatedly printed.
What you should probably do is breaking task into steps.
Get the input
satrt finding the prime numbers from 1 to the max
create a list of already found prime numbers
start a loop from 1 to max
each iteration loop trough already found primes and perform number % prime == 0
if none of numbers in prime numbers can fulfils the condition add number to the list
if found number is greater or equal to min, save the index of it (startIndex).
print the input by iterating trough list from startIndex and printing the numbers
this workflow guarantees you will not consider multiplicant of two big prime numbers as prime number with better performance
You missplaced your first statement, your while-loop is a little bit scary, but here your fix:
import java.util.Scanner;
public class PrimeN{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int a,b;
a = sc.nextInt();
b = sc.nextInt();
for(int i = a; i <= b; i++){
int count = 0;
for(int j = 1; j <= i; j++){
if(i%j == 0){
count++;
}
}//count if equals 2 the prime numbers displayed
if(count == 2){
System.out.println(i);a++;
}}}}
Found a way to solve the ques.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
for(int n = a; n <= b; n++){
boolean prime = true;
int i = 2; //1 will be a factor always
while(i <= n/2){
if(n%i == 0){
//is not prime
prime = false;
break;
}i++;
}
if(prime){
System.out.print(n+ " ");
}
}}}
Just remove your while(a<b) around the two for loops and then your code works fine
like this
import java.util.Scanner;
public class PrimeN {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
// System.out.println("a<b");
int i = a;
while(i<=b)
{
int count = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
count++;
}
} // count if equals 2 the prime numbers displayed
if (count == 2) {
System.out.println("a" + a + " i:" + i);
a++;
}
i++;
}
}
}
To find out what the actual error is, print out the values of a,b,i and j in each iteration.
I have problem with the following question:
Write a program that prompts the user to enter an integer, n. The
program will print the following results:
Sum of all even numbers between 1 and n (inclusive)
Sum of all odd numbers between 1 and n (inclusive)
Here the code I have so far, when I hit run I am getting exponentially large numbers that keep multiplying. I am aware my code is wrong. I dont know what I am doing wrong. Thank you.
package assig;
import java.util.Scanner;
public class Assignment4_Question1 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter an integer: ");
int n = in.nextInt();
int evenSum = 0;
int oddSum= 0;
for (int i = 1; 1<=n; i++){
if(i % 2 == 0){
evenSum = evenSum + i;
} else if (i % 2 != 0){
oddSum = oddSum + i;
}
System.out.println(evenSum);
System.out.println(oddSum);
}
}
You loop is never ending !
for (int i = 1; 1<=n; i++)
So you are saying the loop will go infinte if you n is bigger than 1!
for (int i = 1; i<=n; i++)
The difference in here that you loop will go until i reach to n.
You must change :
for (int i = 1; 1<=n; i++)
to:
for (int i = 1; i<=n; i++)
I have to work on a question for college using arrays this is it:
Write a Java program that will create an array of size 10 and into it put the first 10 even numbers greater than the given user input.
This is what I'm trying but I can't get the right output
import java.util.Scanner;
public class EvenNumbers
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
int array[]=new int[10];
System.out.println("Please enter a number:");
int num = scan.nextInt();
num+=1;
int i=0;
while(i<10)
{
if(num/2==0)
{
array[i]=num;
num++;
i++;
}
else
num++;
}
for(int j=0; j<array.length; j++)
{
System.out.print(array[j]);
}
}
}
You should check num%2==0 instead of num/2==0
And also you can simplify your program by iterating only on even numbers:
num++;
if (num % 2 == 1) // make sure that num is even
num++;
for(int i = 0; i < 10; i++)
{
array[i] = num;
num += 2; // jump to the next even number
}
you can use if (n % 2 == 0) because if (n % 2 == 0) would run if n was even (n can be divided evenly by 2). if (n % 2 == 1) would run if n was odd.the % sign is called mod. Its like dividing and getting the remainder.
Try this :)
import java.util.Scanner;
public class EvenNumbers
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
int array[]=new int[10];
System.out.println("Please enter a number:");
int num = scan.nextInt();
num+=1;
int i=0;
while(i<10)
{
if(num%2==0)
{
array[i]=num;
num++;
i++;
}
else
num++;
}
for(int j=0; j<array.length; j++)
{
System.out.print(array[j]);
}
}
}
Just for fun, you can do it using java-8 IntStream class
IntStream.iterate(++num + num % 2, i -> i + 2).limit(10).forEach(System.out::println);
// ++num; generated numbers should be greater than the given user input
// ++num + num % 2; num variable should be even itself.