Check for perfect number using boolean - java

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.

Related

Program that displays every perfect number

My code runs but for one of the tests two outputs are printed when I only need one. I am unsure of how to avoid this.
This is the task:
Write an application that displays every perfect number from 2 through 1,000. A perfect number is one that equals the sum of all the numbers that divide evenly into it. For example, 6 is perfect because 1, 2, and 3 divide evenly into it and their sum is 6; however, 12 is not a perfect number because 1, 2, 3, 4, and 6 divide evenly into it, and their sum is greater than 12.
The provided template lays out the initial for loop to check each number beginning from 2 and going up to 1,000. In this for loop, the perfect() method is called, where you will submit your piece of code to test if each number follows the conditions described above.
Set result to true if it meets those conditions and use sum to add up the numbers divisible by int n in the method's parameter.
public class Perfect{
public static void main (String args[]){
final int MAX = 1000;
for(int i = 2; i <= MAX; i++)
if(perfect(i) == true)
System.out.println("The number " + i + " is perfect");
}
public static boolean perfect(int n){
int sum = 1;
int i;
boolean result = false;
for (i = 2; i < n / 2; i++) {
if (n % i == 0) {
sum += i;
}
}
if (sum == i) {
return true;
}
else {
return false;
}
}
}
My output:
The number 496 is perfect
The number 729 is perfect
Expected output:
The number 496 is perfect
It only expects the first line printed...
You need to compare sum to the original number n, not to i. And you need to add 1 to the loop condition or it will miss the last divider in even numbers
public static boolean perfect(int n){
int sum = 1;
for (int i = 2; i < (n / 2) + 1; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum == n;
}
First, I don't know if you have used the correct formula. But, you should know that the first perfect number are 6, 28, 496 and 8128. 729 is not a perfect number.
Hope it helped.
public static void main(String[] args) {
int i, j, s;
System.out.println("Perfect numbers 1 to 1000: ");
for(i=1;i<=1000;i++){
s=0;
for(j=1;j<i;j++){
if(i%j==0){
s=s+j;
}
}
if(i==s){ //if i == s is perfect
System.out.println(i);
}
}
}
}
According to the question, you have to print all perfect numbers.
I have created a small snippet, try it and see.
public void printPerfect() {
for(int i=2;i<1000;i++) {
List<Integer> l =factors(i);
int sum =0;
for (Integer factor : l) {
sum+=factor;
}
if(sum==i) {
System.out.println("perfect-- " +i);
}
}
}
List<Integer> factors(int number) {
List<Integer> l = new ArrayList<Integer>();
for(int i = 1; i <= number; ++i) {
if (number % i == 0) {
if(i!=number)
l.add(i);
}
}
return l;
}
You checked sum == i instead of sum == n.
As 729 = 3^6 : 3, 243, 9, 81, 27.
public static boolean perfect(int n) {
int sum = 1;
for (int i = 2; i <= n / 2 && sum <= n; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum == n;
}

Prime problems java

A prime number is a positive integer greater than 1 that is divisible only by itself and 1. In this assignment you are responsible to write a complete Java program to display first N prime numbers. In other words, your program should list the first N prime numbers.
Functional Requirements
Your program should prompt the user for a positive number, or a value of -1 to terminate the program. If the user enters 0, or a negative number, the program will also end immediately.
Your program will display the first N prime numbers given by the user. For example, if the user enters 3, the program should display: “2, 3, 5” which are the first three prime numbers. If the user enters 6, the output would be: “2, 3, 5, 7, 11, 13”.
Sample Run
Welcome to the list of N prime numbers program!
===============================================
Please enter the value of N (positive integer):
6
First 6 prime numbers are:
2
3
5
7
11
13
When i worked on it i got this but need help finishing
import java.util.Scanner;
public class prime {
public static void main(String[] args) {
System.out.print("Welcome to the list of N prime numbers program! \n========================================================\nPlease enter the value of N (positive integer): ");
Scanner scan = new Scanner(System.in);
int n;
int status=1;
int num=3;
n = scan.nextInt();
if(n>=1) {
System.out.println(2);
for(int count=2; count<=n; count++) {
for(int j=2; j<=Math.sqrt(num);j++) {
if(num%j==0) {
status =0;
break;
}
if(status!=0) {
System.out.println(num);
count++;
}
}
status=1;
num++;
}
}
}
}
you should give a out.println("enter the number of prime numbers needed");
then read it using scanner(for example if it is reading into x) and provide a if condition as
if(x<=0)
{
break;
}
and balance code can be given in the else condition.
public class prime {
public static boolean isPrime(int n) {
for(int j=2; j<=Math.sqrt(n)+1;j++) { //Math.sqrt(n) + 1 because you want to check more than half of the original value.
if(n%j==0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.print("Welcome to the list of N prime numbers program! \n========================================================\nPlease enter the value of N (positive integer): ");
Scanner scan = new Scanner(System.in);
int inputNum; //try making the variable name meaningful
inputNum = scan.nextInt();
int count = 0;
int startingVal = 2;
while(count<inputNum) {
if(inputNum==-1) {
break;
}
if(count==0) {
System.out.println(2);
count++;
}
else if(isPrime(startingVal)) {
System.out.println(startingVal);
count++;
}
startingVal ++;
}
}
}
This should work fine. As #Amadan in the comment section already mentioned, your program did not work because your if(status!=0) is in the for loop.
Also, setting the variable names meaningful helps you fix or edit your code easier.
please use below method to get prime no.
static List<Integer> nthPrimeNo(int nth){
List<Integer> integers = new ArrayList<>();
int num, count, i;
num=2;
count=0;
for (int j = 0; j < nth; j++) {
while (count < j){
num=num+1;
for (i = 2; i <= num; i++){
if (num % i == 0) {
break;
}
}
if ( i == num){
count = count+1;
}
}
integers.add(num);
}
return integers;
}
Or do you want to get 10 greater than primes number,
static List<Integer> sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}
List<Integer> primeNumbers = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i]) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
use this function call System.exit(0); in exit condition

Why is my algorithm not giving the expected output?

I am trying to create an Java implementation of the Sieve of Eratosthenes algoritm.
I have the following code, which runs, although gives an incorrect output.
import java.util.ArrayList;
public class sieveOfEratosthenes {
private static final ArrayList<Integer> test = new ArrayList<>();
public static void main (String [] args) {
java.util.Scanner tempInput = new java.util.Scanner(System.in);
System.out.println("What number would you like the prime numbers to be generated to?");
int maxPrime = tempInput.nextInt();
for(int i = 2; i <= maxPrime; i++) {
test.add(i);
}
getPrimeList(maxPrime);
}
private static void getPrimeList(int maxNumber) {
int sqrtOfNum = (int) Math.sqrt(maxNumber);
int temp = 0, i = 0;
int currentPrime = test.get(i);
boolean completed = false;
i++;
//do {
while((completed == false) && (i < test.size())) {
if(i >= test.size()) {
completed = true;
} else if((temp <= sqrtOfNum) ) {
removeMultiples(currentPrime);
}
i++;
if (i < test.size()) {
currentPrime = test.get(i);
}
}
//}while(completed == false && (i < test.size()));
System.out.println("Prime numbers upto: " + maxNumber + ": " + test);
}
private static void removeMultiples(int primeToTest) {
ArrayList<Integer> temp = new ArrayList<>();
for (Integer toTest : test) {
if (!(((toTest) % primeToTest) == 0)) {
temp.add(toTest);
}
}
test.clear();
test.addAll(temp);
}
}
An example of the output given by the program is as follows:
What number would you like the prime numbers to be generated to?
10
Prime numbers upto: 10: [3, 5, 9]
Obviously the output for the above example should be:
Prime numbers upto: 10: [2, 3, 5, 7]
You initialize test to be [2,3,4,5...], set currentPrime to 2 (test[0]), remove multiples of this (removing the 2). I believe a similar things happens when i gets to be 2 and test[2] = 7.
This does not happen with 3 and 5 because you are using i to advance through test, but are also removing items from test so that the values i references changes (because the value in that position has changed). So at the end of the first time through the while loop, i has been advanced to 2 without ever eliminated multiples of 3 or 5 (which you'd see if you used a bigger maxNumber).
The Sieve of Eratosthenes algorithm says that when you consider a prime currentPrime you have to mark as non-primes all its multiples except from itself. In your removeMultiples function you are removing also currentPrime.
The way you iterate in getPrimeList seems also a bit odd to me. I think you might get rid of the completed variable and of some i >= test.size() testing.
Try something like:
import java.util.ArrayList;
public class sieveOfEratosthenes {
private static final ArrayList<Integer> test = new ArrayList<>();
public static void main (String [] args) {
java.util.Scanner tempInput = new java.util.Scanner(System.in);
System.out.println("What number would you like the prime numbers to be generated to?");
int maxPrime = tempInput.nextInt();
for(int i = 2; i <= maxPrime; i++) {
test.add(i);
}
getPrimeList(maxPrime);
}
private static void getPrimeList(int maxNumber) {
int sqrtOfNum = (int) Math.sqrt(maxNumber);
int temp = 0, i = 0, current_prime = 0;
//do {
while(current_prime <= sqrtOfNum && i < test.size()) {
current_prime = test.get(i);
removeMultiples(current_prime);
i++;
}
//}while(completed == false && (i < test.size()));
System.out.println("Prime numbers upto: " + maxNumber + ": " + test);
}
private static void removeMultiples(int primeToTest) {
ArrayList<Integer> temp = new ArrayList<>();
tmp.add(primeToTest);
for (Integer toTest : test) {
if (toTest%primeToTest != 0) {
temp.add(toTest);
}
}
test.clear();
test.addAll(temp);
}
}

How to factor a number and determine whether its a prime number

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

Finding factors of a given integer

I have something like this down:
int f = 120;
for(int ff = 1; ff <= f; ff++){
while (f % ff != 0){
}
Is there anything wrong with my loop to find factors? I'm really confused as to the workings of for and while statements, so chances are they are completely wrong.
After this, how would I go about assigning variables to said factors?
The following code will return a list of all factors of a given number:
public ArrayList<Integer> findFactors(int num) {
ArrayList<Integer> factors = new ArrayList<Integer>();
// Skip two if the number is odd
int incrementer = num % 2 == 0 ? 1 : 2;
for (int i = 1; i <= Math.sqrt(num); i += incrementer) {
// If there is no remainder, then the number is a factor.
if (num % i == 0) {
factors.add(i);
// Skip duplicates
if (i != num / i) {
factors.add(num / i);
}
}
}
// Sort the list of factors
Collections.sort(factors);
return factors;
}
This answer improves Sharad Dargan's answer in two ways:
Based on an idea used in this answer, you can speed up the solution by determining the value to increment by, based on whether the number is even or odd.
Add the following line of code before the for loop:
int incrementer = num % 2 == 0 ? 1 : 2;
Then change the last part of the loop to:
i += incrementer
If the number is odd, it then will skip all even numbers, rather than always incrementing by one no matter what.
Sharad stores the upper limit value in a variable and then uses that variable in the for loop:
int upperlimit = (int)(Math.sqrt(a));
...
for(int i = 1; i <= upperlimit; i+= 1)
Instead, place Math.sqrt(num) directly in the for loop and skip the upper limit variable:
for (int i = 1; i <= Math.sqrt(num); i += incrementer) {
This will allow you to skip the casting part of the code, creating cleaner code.
Some JUnit test cases you can then use:
#Test
public void test12() {
FindFactors find = new FindFactors();
int num = 12;
List<Integer> factors = Arrays.asList(1, 2, 3, 4, 6, 12);
assertEquals(factors, find.findFactors(num));
}
#Test
public void test1000000() {
FindFactors find = new FindFactors();
int num = 1000000;
List<Integer> factors = Arrays.asList(1, 2, 4, 5, 8, 10, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 160, 200,
250, 320, 400, 500, 625, 800, 1000, 1250, 1600, 2000, 2500, 3125, 4000, 5000, 6250, 8000, 10000, 12500,
15625, 20000, 25000, 31250, 40000, 50000, 62500, 100000, 125000, 200000, 250000, 500000, 1000000);
assertEquals(factors, find.findFactors(num));
}
#Test
public void test1() {
FindFactors find = new FindFactors();
int num = 1;
List<Integer> factors = Arrays.asList(1);
assertEquals(factors, find.findFactors(num));
}
#Test
public void test0() {
FindFactors find = new FindFactors();
int num = 0;
List<Integer> factors = new ArrayList<Integer>();
assertEquals(factors, find.findFactors(num));
}
Here is how to get all factors of the given number.
public class Factors {
public static void main(String[] args){
int n = 420;
for(int i=2; i<=n; i++){
while(n%i==0){
System.out.println(i + "| " + n);
System.out.println(" -----");
n = n/i;
}
}
}
}
Output:
2| 420
-----
2| 210
-----
3| 105
-----
5| 35
-----
7| 7
-----
public class Solution {
public ArrayList<Integer> allFactors(int a) {
int upperlimit = (int)(Math.sqrt(a));
ArrayList<Integer> factors = new ArrayList<Integer>();
for(int i=1;i <= upperlimit; i+= 1){
if(a%i == 0){
factors.add(i);
if(i != a/i){
factors.add(a/i);
}
}
}
Collections.sort(factors);
return factors;
}
}
The above solution simply works like calculating prime factors.
The difference being for every prime factor we keep calculating the other part of the product i.e the reqd number.
In order to find the factors of a given number, you only need to check upto the square root of the given number.
For example, in order to find the factors of 6, you only need to check till 2.45 (√6). The factors of 6 will be 1 and 2, and their converse numbers, i.e. 3 and 6.
I have made a program that determines the factors of a given number and displays them. Here is the necessary code:
Scanner input = new Scanner(System.in);
System.out.print("Enter integer: ");
long num = input.nextLong();
for(long i = 1; i <= Math.sqrt(num); i++) {
if(num % i == 0) {
System.out.println(i);
if(i != num/i) {
System.out.println(num/i);
}
}
}
You just need this program to find the factors of a given number. However, if you want to take it a step further and display the factors arranged in ascending order, then the necessary code is as follows:
Scanner input = new Scanner(System.in);
System.out.print("Enter integer: ");
long num = input.nextLong();
ArrayList<Long> list1 = new ArrayList<>(), list2 = new ArrayList<>();
long currentTime = System.currentTimeMillis();
for(long i = 1; i <= Math.sqrt(num); i++) {
if(num % i == 0) {
list1.add(i);
if(i != num/i) {
list2.add(num/i);
}
}
}
int n1 = list1.size() - 1;
int n2 = list2.size() - 1;
for(int i = 0; i <= n1; i++) {
System.out.println(list1.get(i));
}
for(int i = n2; i >= 0; i--) {
System.out.println(list2.get(i));
}
What this does: This program stores the factors of the number upto the number's square root in one list (list1), and the converse of these numbers in another list (list2). It then prints the elements of both lists (as shown).
There's nothing wrong with your for loop, but a while loop is the wrong thing to be using here.
The logic of your for loop is:
Set ff to 1.
Keep going while ff <= f.
After you've done everything in the for loop, add 1 to ff.
This looks like it is exactly as you want.
The while loop isn't right, though. It will continue to do whatever code you write there for as long as ff is a factor of f, so unless you change them in the while code, you'll get an infinite loop. However, changing that to an if statement will give you what you want.
Since you're checking for factors, you don't actually need to check all possibilities up to f - only up to the square root of f. Whenever you find that ff is a factor, output both ff and f/ff as factors, unless f is a sqare number.
public static void printFactors(int number) {
if (number < 1 )
System.out.println("Invalid Value");
for (int i = 1 ; i <= number ; ++i) {
if ( number % i == 0)
System.out.println(i);
}
}
}
It looks like you are not going to do something with either f or ff in your while loop? If so, the expression f%ff != 0 is either false (and then it will go to the next in the for loop), or it is true, and it will end up in an infinite loop.
Are you sure you need the while like this?
Slightly modified solution: You can first check if variable x is divisible by variable y. If yes, we will count 1 and will repeat this process. For the loop counter, x/y is used and you should check x>0 to avoid repetition when x becomes zero but loop is not finished yet.
public class Factor {
public static void main(String[] args) {
int x = 48;
int x1 = x;
int y = 2;
int k = x / y;
int j = 0;
for (int i = 1; i < k; i++) {
if ((x % y) == 0 && x > 0)
j++;
x = x / 2;
}
System.out.println(+x1 + " is a factor of " + y + " for " + j
+ " times.");
}
}
I got all the factors just fine with this (I just modified the algorithm in the question).
int num1 = 120;
for(int num2=1;num2<=num1;num2++)
{
if (num1%num2 != 0)
System.out.println(num2);
}
import java.util.Scanner;
public class Factors
{
Scanner scn=new Scanner(System.in);
int num=scn.nextInt();
public void findFactor()
{
System.out.println("Factors are");
System.out.println("1");
for(int i=2;i<=num;i++)
{
if(num%i==0)
{
num=num/i;
System.out.println(i);
i=2;
}
}
}
public static void main(String[] args)
{
while(1==1)
{
System.out.println("Enter a Number");
Factors fct=new Factors();
fct.findFactor();
}
}
}
Utilizing Streams introduced in Java 8, the following will print the factors for a given number.
int input = 1500;
IntStream.rangeClosed(1, input)
.filter(e -> input % e == 0)
.forEach(System.out::println);
This is how you write it yourself like a boss. Needs to add if statements to handle one and two, but besides that; this method is as sexy as it gets
public static void primerize(int n){
boolean reduced = false;
while(n > 2){
if(n%2 == 0){
System.out.println(2 + "," + n/2);
n /= 2;
}
else{
int i = isPrime(n);
if(i == n && reduced == false){
System.out.println(1 + "," + n);
n /= n;
}
else if(i == n){
n/= n;
}
else{
System.out.println(i + "," + n/i);
n = i;
reduced = true;
}
}
}}
public static int isPrime(int n){
for(int i = (n/3); i > 0; i--){
if(i == 1){
return n;
}
else if(n%i == 0){
return i;
}
}
return 0;}
This code will give you the factors.
ArrayList<Integer> arr = new ArrayList<>();
int x=48;
int y=1;
while(x!=1)
{
if(x%y==0)
{
x=x/y;
arr.add(y);
if(y==1)
{
y++;
}
}
else
{
y+=1;
}
}
System.out.println(arr);
Easiest way using recursive function
public static int factorial(int n){
if(n!=1)
return n*factorial(n-1);
return 1;
}

Categories