I'm a beginner, my code finds all the primes that divide a given number but I want it to also print how many times the prime divides. this is my code:
public static void main(){
Scanner myScanner = new Scanner (System.in) ;
int n = myScanner.nextInt();
int prime = 2 ;
int count = 0 ;
while ( prime <= n ){
if ( n%prime == 0 ) {
n = n/prime ;
System.out.println(prime + " " +count);
}
if ( n%prime !=0 ){
prime = prime + 1;
}
}
}
Hope you'll understand me, thanks!!
您忘记增加计数器了:
System.out.println(prime + " " +(++count));
You need to increase the counter for every division that has a remainder 0
and you must exit the loop once the remainder is not 0
:
public static void main(String[] args) {
Scanner myScanner = new Scanner (System.in) ;
int n = myScanner.nextInt();
int prime = 2;
int count = 0;
while ( prime <= n ){
if ( n % prime == 0 ) {
n /= prime;
count++;
} else
break;
}
System.out.println(prime + " " +count);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.