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
Related
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'm currently being asked to create a machine code that will generate multiple distinct random prime numbers and have it's output be displayed from highest prime number to lowest
i'm already done doing a the isPrime method the output only gives me 1 random prime number.
package isPrime.isPrime;
import java.util.Scanner;
import java.util.Random;
public class Primusnumberus {
public static void main(String[] args) {
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isPrime(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
private static boolean isPrime(int inputNum){
if (inputNum <= 3 || inputNum % 2 == 0)
return inputNum == 2 || inputNum == 3;
int divisor = 3;
while ((divisor <= Math.sqrt(inputNum)) && (inputNum % divisor != 0))
divisor += 2;
return inputNum % divisor != 0;
}
}
I expect the output of
(println)
731
11
971
53
17 and so fort
You have to generate the primes in a loop for example
for(int i = 0; i < 25; i++){ // If you do not want 25 Primes change it here
num = rand.nextInt(1000) + 1;
while (!isPrime(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
Btw.: generating them using Random may result in a very long execution time of your program.
If you just need primes up to 1001 I would recommend generating them all and then just selecting them at random. (using a List for example)
You can run a loop and add those random prime numbers to a list. Then sort the list and print it at the end like below,
package isPrime.isPrime;
import java.util.*;
public class Primusnumberus {
public static void main(String[] args) {
int num = 0;
int numberCount = 24;
int counter = 0;
Random rand = new Random();
List<Integer> primeList = new ArrayList<>();
while (counter < numberCount) {
num = rand.nextInt(1000) + 1;
while (!isPrime(num)) {
num = rand.nextInt(1000) + 1;
}
if (!primeList.contains(num)) {
primeList.add(num);
counter ++;
}
}
Collections.sort(primeList);
System.out.println(primeList);
}
private static boolean isPrime(int inputNum){
if (inputNum <= 3 || inputNum % 2 == 0)
return inputNum == 2 || inputNum == 3;
int divisor = 3;
while ((divisor <= Math.sqrt(inputNum)) && (inputNum % divisor != 0))
divisor += 2;
return inputNum % divisor != 0;
}
}
I have just updated your code to your requirement. But this won't be a good method to get random prime numbers since it might take some time when the number count increases.
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;
}
I wanted to convert decimal to binary and the following code doesn't work.
Please help me to correct the code.
package mainpackage;
import java.util.*;
class MainClass {
public MainClass() {
}
public static int binaryfinder(int n) {
int a[] = new int[8];
int i = 0;
int b = 0;
int n1 = n;
while (n1 > 0) {
a[i] = n1 % 2;
i++;
n1 = n1 / 2;
}
System.out.printf("Binary number of %d is = ", n);
for (int j = i - 1; j >= 0; j--) {
b += ((10 ^ j) * a[j]);
}
return b;
}
public static void main(String[] args) {
System.out.println("\nEnter the number to find its binary value:\n");
Scanner k = new Scanner(System.in);
int num = k.nextInt();
int inBin = binaryfinder(num);
System.out.print(inBin);
}
}
After I click RUN, it asks to enter the binary value and when I enter the value, it says, "Binary number of 0 = " No matter what I enter it always outputs "Binary number of 0 = ".
No errors are thrown.
Integer.toBinaryString(i)
this should do the trick in java
You have an endless loop, thats why your program never terminates:
while (j != 0) {
b += ((10 ^ j) * a[j]);
}
After I click RUN, it asks to enter the binary value and when I enter the value, it says, "Binary number of 0 = " No matter what I enter it always outputs "Binary number of 0 = ". No errors are thrown.
Never ending while loop
while (j != 0) {
b += ((10 ^ j) * a[j]);
}
You are changing value of n and finally after while loop :n = 0 and so the output
while (n > 0) {
a[i] = n % 2;
i++;
n = n / 2;
}
System.out.println(output);
Your program (as whole) is incorrect
Other Options:
1) Use Integer.toBinaryString()
2) Use the basic formula to convert decimal --> binary
int n = 10;
String output = "";
do {
output = (n % 2) + output; // reverse string
n = n / 2;
} while (n > 0);
I am working on a school assignment, so I am looking for guidance on what I am doing wrong. This is part of a larger program, but I am trying to work on loop before I implement the rest of the program. Basically, my loop is suppose to iterate through all the number and then add every other number, for example:
if the number entered is 48625, then return the sum of 5+6+4. I figured that I would have to combine my loop with an if statement to iterate through each nth number, so this is what I worked out so far:
class testLoop{
public static void main (String args[]){
int num = 12345;
int sum = 0;
for(int i = 0; num > 0; i++)
{
if(i%num == 0)
{
sum += num % 10;
}
num /= 10;
System.out.println(sum);
}
}
}
Unfortunately, this is not working. It returns 6,5,5,5,5. It is not adding the nth values as planned.
I also tried the following:
int num = 12345;
int sum = 0;
while(num > 0) {
sum += num % 10;
num /= 10;
}
But that did not work either, it returned 15, which is basically the sum of all digits in variable num. I know I am close to a solution, it's somewhere between my two codes, but I can't seem to get it right.
Simply divide by 100. That will skip the even numbers.
int num = 12345;
int sum = 0;
while(num > 0) {
sum += num % 10;
num /= 100;
}
int num = 12345;
int sum = 0;
int pos = 0;
while(num > 0) {
int digit = num % 10; // make it really blatantly clear what the DIGIT is
if (pos % 2 == 0)
sum += digit;
num /= 10;
pos++;
}
You needed a checking mechanism to ensure you're skipping half the digits. [You're trying to add digits of the number, not numbers. Editor.]
This would also fix your first solution:
if(i%2 /*not num*/ == 0)
int num = 12345;
int sum = 0;
String str = String.valueOf(num);
for (int i = str.toCharArray().length - 1, j = 0; i >= 0; i--, j++) {
if (j % 2 == 0) {
int number = Character.digit(str.charAt(i), 10);
sum += number;
}
}
System.out.println(sum);