java - Prime factorization in a program for class -


import java.util.scanner;  public class javaapplication1 {   public static void main(string[] args) {     scanner kboard = new scanner(system.in);     int n = 0;     int = 1;      system.out.println("enter positive number");     n = kboard.nextint();     system.out.print("the prime factors of " + n + " : ");     value = 2;     while (n > 1) {         = 1;         if (n % != 0){            = 1;            i=i+1;            if(n % == 0){                system.out.println(" "+ i);            }         }         else {             system.out.print("1 , " + n);             break;         }     }    } } 

this program , started coding month or ago, program giving 1 , number output rather prime factors.

the program gives 1 output because of this:

i = 1; if (n % != 0) {     // ... } else {     system.out.print("1 , " + n);     break; } 

since i = 1, n % != 0 false, because n module 1 0. else block gets executed , break out of while loop.

even if fix this, there many other issues in program:

  • the condition n > 1 non-sense, n never changes in loop, condition true.
  • checking % 1 pointless, every number divided 1. should start checking 2.

with minor improvements, loop can improved find factors:

list<integer> factors = new arraylist<>(); (int = 2; <= math.sqrt(n); i++) {     if (n % == 0) {         factors.add(i);     } } 

but not enough. find factors, not prime factors. example, number 40, find 2, 4, 5, 8, 10, of 2 , 5 primes. 1 simple solution add method called isprime checks if number prime.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -