It counts up to 5 and sum of 5 even numbers. I did it but it didn't work correctly(Mistake is about calculating the sum).Can you look at it ?
Here the code:
package com.java.ornekler;
public class Main {
public static void main(String[] args) {
int n = 1;
int count = 0;
int sum = 0;
do {
isEven(n);
if (!isEven(n)) {
n++;
continue;
} else {
System.out.println(+n + " is a even number ");
n++;
sum = sum + n;
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
}
}
while (n <= 10);
}
public static boolean isEven(int n) {
if ((n % 2) == 0) {
return true;
} else {
return false;
}
}
}
Output is:
2 is a even number
4 is a even number
6 is a even number
8 is a even number
10 is a even number
Sum is : 35
n++;
sum = sum + n; // here you incremented n then added to sum.
change to
sum = sum + n;
n++;
The reason why your sum is at 35 is because you increment your n one more time before you sum it together. Your total is 30 + numberOfN = 35
Your else statement should look like this
else {
System.out.println(+n + " is a even number ");
sum = sum + n;
n++; // this was above and should be here
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
When you find an odd number, you do this:
System.out.println(+n + " is a even number ");
n++;
sum = sum + n;
So, if n==4, first you bump it up so that n==5. Then you add it to sum, so sum increases by 5, not 4.
So fix this, add to sum before incrementing n.
More generally, instead of jumping up in ones, testing for even-ness, why not start on an even number, and jump up in twos?
And, rather than having a println and a break in an if within the loop, make it an exit condition of the loop, and put the println after the loop.
Along with comments above and you have duplicity statement: n++;.
Put that statement after if{}else{} block.
Revise the code as follows:
do {
isEven(n);
if (!isEven(n)) {
continue;
} else {
System.out.println(+n + " is a even number ");
sum = sum + n;
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
}
n++;
}
while (n <= 10);
Java 8 syntax might be easier to follow using predefined functions for summing and limiting
package test.test;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Snippet {
public static void main(String args[]) {
int sum = IntStream.iterate(1, i -> i + 1).limit(10).filter(isEven()).peek(Snippet::printEvenNumber).sum();
System.out.println("Sum is : " + sum);
}
private static void printEvenNumber(int i) {
System.out.println(i + " is an even number");
}
private static IntPredicate isEven() {
return i -> i % 2 == 0;
}
}
Related
Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and
7 are twin primes, and 11 and 13 are twin primes. Write a Java program TwinPrimes.java that prompts
the user to input the search range of twin primes, display all the twin primes (2 pairs per line) within
the range, and print the number of twin primes found. The search range is assumed to be positive and
your program should repeatedly perform the same task until a sentinel value of -1 is entered.
The expected output of your program should be as follows:
Round 1:
Enter the search range: 100
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
Number of twin primes less than or equal to 100 is 8
Round 2:
Enter the search range: 150
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
......(Omitted)
Number of twin primes less than or equal to 200 is 15
Round 4:
Enter the search range: -1
End
I know that I am not complected the code, but I am struggling on how to print the Prime numbers in ( , ) ( , )way and how to calculate the number of twin primes show it at the end.
The below coding is what I had to do:
import java.util.Scanner;
import java.util.Random;
public class TwinPrimes {
public static void main(String[] args) {
int i = 0;
int A, B = 0, D = 0;
int num = 0;
System.out.println("Round" + " " + ++i + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
A = scn.nextInt();
{
if (A < 0)
System.out.println("End");
}
for (i = 3; i <= A; i++) {
int counter = 0;
for (num = B; num >= 1; num--) {
{
if (B % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
}
}
System.out.println("(" + i + "," + i + ")" + " " + "(" + i + "," + i + ")");
// sum Number of twin primes to
System.out.println("Number of twin primes less than or equal to " + A + " " + "is" + " ");
return;
}
}
}
package array1;
import java.io.IOException;
import java.util.Scanner;
public class Mainclass {
public static void main(String args[]) throws NumberFormatException, IOException
{
int a,k=0,line=0,count=0;
while(true)
{
System.out.println("Round" + " " + ++k + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
a= scn.nextInt();
{
if (a< 0)
{
System.out.println("End");
System.exit(0);
}
}
System.out.println("The Twin Prime Numbers within the given range are : ");
for(int i=2; i<=(a-2); i++)
{
if(isPrime(i) == true && isPrime(i+2) == true)
{
System.out.print("("+i+","+(i+2)+") ");
line++;
if(line==2)
{
System.out.println();
line=0;
}
count++;
}
}
System.out.println();
System.out.println("the number of twin prime numbers less than or equal to"+a+"is"+count);
}
}
static boolean isPrime(int n) //funton for checking prime
{
int count=0;
for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
if(count == 2)
return true;
else
return false;
}
}
I am struggling on how to print the Prime numbers in ( , ) ( , ) way
You may use String.format. See How to use String.format in Java?
For example, String.format("Found pair (%d,%d)", prime1, prime2);
How to calculate the number of twin primes show it at the end.
Simply keep a counter, say int counter when you're looking for the prime pairs.
import java.util.Scanner;
public class Main {
// Consider writing a helper function to check primality
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int max_number = 100;
int counter = 0; // keep a count
for (int i = 2; i+2 < max_number; i++) {
if (isPrime(i) && isPrime(i+2)) {
counter++; // increment counter
String msg = String.format("Found pair (%d,%d)", i, i+2);
System.out.println(msg);
}
}
System.out.println("Total number of pairs is " + counter);
// Total number of pairs is 8
}
}
I have problem with my Java coding to find the perfect number using boolean method. I want to print out like this:
Example :
‘6 is a perfect number. 6 is the sum of 1, 2, 3’
Otherwise :
‘9 is not a perfect number’
But I don't know how to make the coding for "6 is the sum of 1, 2, 3". Can anyone help me?
Here is my coding :
import java.util.Scanner;
public class trial
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner perfect = new Scanner(System.in);
System.out.print("Enter any integer number : ");
int n = perfect.nextInt();
if(isPerfectNumber(n))
{
System.out.println(n+" is a perfect number");
}
else
{
System.out.println(n+" is not a perfect number");
}
}
public static boolean isPerfectNumber(int n)
{
int sum = 0;
for (int i=1; i<n; i++)
{
if (n%i == 0)
{
sum = sum + i;
}
}
if (sum == n)
{
return true;
}
else
{
return false;
}
}
}
Well, you already know how to get the factors of the number, as per the if (n%i == 0) line.
So, hint only since this is almost certainly class work.
At the same point you add the factor to the sum, you should add it to a list of some description and have that made available to the calling function.
One possibility would be to return a list, the second and subsequent elements being all the factors of the given number, and the first element being the sum of those.
So, for 6, you would get the list {6, 1, 2, 3}, 12 would give you {16, 1, 2, 3, 4, 6}, and 7 would give you {7, 1}.
That way, you simply have to check the original number against the first element and, if they're equal, print out the other elements. In other words, pseudo-code such as:
input num
factorList = getFactorList(num)
if factorList[0] == num:
print num, " is perfect, factors are:"
for idx = 1 to factorList.size() - 1 inclusive:
print " ", factorList[idx]
println "."
else:
println num, " is not perfect."
I'd change isPerfectNumber to return a List of the factors that make n or null if it's not a perfect number. Then you have a single result that both contains factors and can be used to determine if n is perfect:
public static void main(String[] args) {
Scanner perfect = new Scanner(System.in);
System.out.print("Enter any integer number : ");
int n = perfect.nextInt();
List<Integer> factors = getPerfectFactors(n);
if (factors != null) {
System.out.println
(n + " is a perfect number. It's the sum of" +
factors.stream()
.map(String::valueOf)
.collect(Collectors.joining(", "));
} else {
System.out.println(n+" is not a perfect number");
}
}
public static List<Ingeger> getPerfectFactors(int n) {
int sum = 0;
List<Ingeger> factors = new LinkedList<>();
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum += i;
factors.add(i);
}
if (sum > n) { // Early return optimization, not material to the solution
return null;
}
}
if (sum == n) {
return factors;
} else {
return null;
}
}
Well in the for loop if condition if modulus is true then you know the i has to be kept in track somehow.
So I would
declare an arraylist of integers to keep track of summation numbers.
ArrayList<Integer> numbs = new ArrayList<Integer>();
Then
public static boolean isPerfectNumber(int n)
{
int sum = 0;
for (int i=1; i<n; i++)
{
if (n%i == 0)
{
numbs.add(i); //here keep track of those summation numbers
sum = sum + i;
}
}
if (sum == n)
{
return true;
}
else
{
return false;
}
}
Now while printing you can do like
System.out.println(n + " is a perfect number. " + n + " is sum of " + StringUtils.join(numbs, ","));
Don't forget to import StringUtils: import org.apache.commons.lang3.StringUtils commons-lang3 library.
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
public class helloworld {
public static int[]array = new int[28124];
public static List<Integer> abundant = new ArrayList<Integer>();
public static void main(String []args)
throws IOException {
System.out.println("Answer: " + SumNonAbundant());
}
public static int SumNonAbundant() {
int sum = 0;
abundant.add(12);
GetAbundant(28123);
for (int i = 1; i <= 28123; i++) {
if (checkForSum(i)) {
System.out.println(i);
sum+=i;
}
}
return sum;
}
public static int SumOfDivisors(int num) {
int sum = 0;
for (int i = num - 1; i > 0; i--) {
if (num % i == 0) {
sum += i;
}
}
return sum;
}
public static void GetAbundant(int num) {
for (int i = 13; i <= num ; i++) {
int sum = SumOfDivisors(i);
if ( sum > i) {
System.out.println(i + " " + sum);
abundant.add(i);
}
}
}
public static boolean checkForSum(int num) {
int start = 0;
int end = abundant.size() - 1;
while (start < end) {
if (abundant.get(start) == num) {
return false;
}
else if (abundant.get(end) == num) {
return false;
}
else if (abundant.get(start)*2 == num) {
return false;
}
else if (abundant.get(end)*2 == num) {
return false;
}
else if (abundant.get(start) + abundant.get(end) == num) {
return false;
}
else if (abundant.get(start) + abundant.get(end) < num) {
start++;
}
else if (abundant.get(start) + abundant.get(end) > num) {
end--;
}
}
return true;
}
}
When I run this code, I get "Answer: 4178876", however, the correct answer I think is 4178971.
Really not sure whats the issue here, feel like I'm missing something small but I can't see it. Any help would be greatly appreciated.
in checkForSum change
if (abundant.get(start) == num) {
return true; // not false
}
and remove
else if (abundant.get(end) == num) {
...
}
try
public static boolean checkForSum(int num) {
int start = 0;
int end = abundant.size() - 1;
while (start < end) {
if (abundant.get(start) == num) {
return true;
}
else if (abundant.get(start)*2 == num) {
return false;
}
else if (abundant.get(end)*2 == num) {
return false;
}
else if (abundant.get(start) + abundant.get(end) == num) {
return false;
}
else if (abundant.get(start) + abundant.get(end) < num) {
start++;
}
else if (abundant.get(start) + abundant.get(end) > num) {
end--;
}
}
return true;
}
This is an old question, but I recently ran across this exact same issue (my answer was also 4178876, off by 995), and the only other answer didn't help me figure out what I was doing was wrong.
My issue was that I was removing the abundant numbers themselves as well as those numbers that are the sums of two abundant numbers. That is, I was removing 12, 18, 20 ... as well as 12 + 12, 12 + 18, 12 + 20, 18 + 20, ...
The singletons should not be removed before summing.
I am printing the factorial of the first 10 numbers, so it is 0 - 9. The below code works for me. But I am unable to make the loop such that the factorial of 0 is within the loop too. Any advice is appreciated. Thank you.
public class fact {
public static void main(String[] args) {
System.out.println("\n\n(f) Loop to print first 10 factorial numbers");
System.out.println("\nFactorial of 0 is 1");
int fact = 1;
int index = 1;
while (index < 10)
{
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
index++;
}
}
}
How about adding an if condition in your while loop for index 0
int fact = 1;
int index = 0;
while (index < 10)
{
if(index == 0)
System.out.println("\nFactorial of 0 is 1");
else {
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
}
index++;
}
The factorial of 0 is a special case, so you are better off printing it outside the loop, just as you are doing now.
For big n numbers find factorial and its digit count .
import java.util.Scanner;
public class N_Faktorial {
public static void main(String [] args)
{
int u=1,A[]=new int[9999999];
Scanner scan =new Scanner(System.in);
System.out.print("n=");
int n=scan.nextInt();
A[1]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++) {
A[j]*=i;
}
for(int j=1;j<=n;j++)
{
if(A[j]>9)
{
A[j+1]+=A[j]/10;
A[j]%=10;
}
if(A[u+1]!=0) {
u++;
}
}
}
System.out.print(n+"! digit count:"+u+"\\n Result: \\n");
for(int i=u;i>=1;i--)
{
System.out.print(A[i]);
}
}
}
factorialList(10);
public static int factorialList(int indexMax) {
int fact = 1;
if (indexMax > 0) fact = indexMax * factorialList(indexMax - 1);
System.out.println("Factorial of " + indexMax + " is " + fact);
return fact;
}
Fn calls are less effective than loops but I bet it would be optimized to ~ the same on task of this size.
You can do like this
int fact = 1;
int index = 0;
while (index < 10)
{
fact=(index==0)?1:fact*(index);
System.out.println("Factorial of " + index + " is " + fact);
index++;
}
So i have this problem where when i factor a number, lets say 15, i have to display this: 15=3x5 but instead what i get is 3x5x5 and i have no clue of how to make it that so it only displays 3x5. And then another problem i have is to find whether the number i inputted is a prime number or not. Any way of fixing this? I just need that and the other stuff im gonna edit after that.
public class PrimeFactor
{
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
int a;
int d;
int remainder=0;
int count=2;
int c=0;
String s;
System.out.println("Enter an integer to be factored:");
a=input.nextInt();
s="";
d=a;
while(a>1)
{
if(a>1)
{
s="";
while(a>1)
{
remainder=a%count;
if (!(remainder>0))
while(remainder==0)
{
remainder=a%count;
if (remainder==0)
{
a=a/count;
c=c+1;
s=s+count+"x";
if (a==1)
s=s+count;
}
else
count++;
}
else
count++;
}
if (a%count==0)
{
System.out.println(d +"=" + s);
System.out.println(d+" is a prime number.");
}
else
System.out.println(d +"=" + s);
}
// TODO code application logic here
}
}
}
This determines if the number is prime or not the quickest way. Another method would be to use a for loop to determine the number of factors for the number and then say it's prime if it has more than two factors.
int num; // is the number being tested for if it's prime.
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) // only have to test until the square root of the number
{
if (num%i == 0) // if the number is divisible by anything from 2 - the square root of the number
{
isPrime = false; // it is not prime
break; // break out of the loop because it's not prime and no more testing needed
}
}
if (isPrime)
{
System.out.println(num + " is a prime number.");
}
else
{
System.out.println(num + " is a composite number.");
}
You are not constructing the factorization string quite right:
When you find that 3 divides a=15 you set s to 3x and set a to the quotient, so a=5
When you find that 5 divides a=5 you append 5x to s, so now s is 3x5x. Then you set a to the quotient, which is 1. Since the quotient is now 1, you append 5 again, so now you get 3x5x5.
What you'll want to do is append only 5 when a=1, not 5x5. You have to change this:
s=s+count+"x";
if (a==1)
s=s+count;
to this:
if (a==1) {
s=s+count;
} else {
s=s+count+"x";
}
How about trying like this:-
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("Number is a prime");
else
System.out.println("Number is not a prime");
break;
}
}
These are quite straight-forward methods you can use to factor a number and determine if it is a prime number:
public static int oneFactor(int i) {
for (int j = 2; j < i; j++) {
if (i % j == 0)
return j;
}
return -1;
}
public static Integer[] primeFactors(int i) {
List<Integer> factors = new ArrayList<Integer>();
boolean cont = true;
while (cont) {
int f = oneFactor(i);
if (i > 1 && f != -1) {
i /= f;
factors.add(f);
} else
factors.add(i);
if (f == -1)
cont = false;
}
return factors.toArray(new Integer[factors.size()]);
}
public static boolean isPrime(int i) {
if (i == 2 || i == 3)
return true;
if (i < 2 || i % 2 == 0)
return false;
for (int j = 3, end = (int) Math.sqrt(i); j <= end; j += 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
I am sure one can use faster algorithms, but those would be at the cost of simplicity, and it doesn't seem like you need high speed methods.
They all operate on ints, but its easy to change them to work with longs.
If you have any questions, feel free to ask!
You want to write a loop which loops through numbers 1 to (Inputted Number). And if you found a factor, you print it and divide the input by the factor. (And test if it can be divided again by the same number), else then skip to the next number.
Keep doing this until your input divides down to 1.
This program will break the number down to prime factors:
public class Factor {
public static void main() {
//Declares Variables
int factor = 15;
int i = 2;
System.out.println("Listing Factors:\n");
while (factor>1) {
//Tests if 'i' is a factor of 'factor'
if (factor%i == 0) {
//Prints out and divides factor
System.out.println(i);
factor = factor/i;
} else {
//Skips to next Number
i++;
}
}
}
}
Output:
Listing Factors:
3
5