① 用java编写用户输入一个整数,求这个整数的因子和(所谓因子即可以被其整除的数,但本身不算,
public class Test1 {
public static void main(String[] args) {
int num = 1845;
int sum = 0;
System.out.println("因子:1");
sum += 1;
int sqrt = (int)Math.sqrt(num);
for(int i=2;i<sqrt;i++){
int j = num%i;
if(j==0){
System.out.println("因子:"+i);
sum += i;
int k = num/i;
System.out.println("因子:"+k);
sum += k;
}
}
System.out.println("因子和:"+sum);
}
}
② Java编写输出一个整数的所有因子
import java.util.Scanner;
public class A {
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int a = in.nextInt();//从控制台读入一个整数,也可以在这直接给a赋给初值
System.out.print(a+"的所有因子是:");
for(int i = 1;i<=a;i++){
if(a%i==0){ //a对i取余,能除尽i就是a的因子
System.out.print(i+" ");//打印这个i值
}
}
}
}
③ java输入一个整数,输出其所有素数因子
importjava.util.ArrayList;
importjava.util.List;
importjava.lang.Math;
publicclassSolution{
privateintnum;
privateList<Integer>primeList;
privateintindex;
publicintgetNum(){
returnnum;
}
publicvoidsetNum(intnum){
this.num=num;
}
publicSolution(intnum){
this.num=num;
primeList=newArrayList<Integer>();
primeList.add(3);
}
publicList<Integer>findPrimeContainedList(){
index=0;
intoperationNum=num;
List<Integer>list=newArrayList<Integer>();
intstop=(int)Math.floor(Math.sqrt(operationNum));
if(stop<=2){
returnlist;
}
operationNum=checkAndRemovePrimeNumber(operationNum,2,list);
stop=(int)Math.floor(Math.sqrt(operationNum));
intp=getNextPrimeNumber();
while(p<=stop){
operationNum=checkAndRemovePrimeNumber(operationNum,p,list);
stop=(int)Math.floor(Math.sqrt(operationNum));
p=getNextPrimeNumber();
}
list.add(operationNum);
returnlist;
}
(intnum,intp,List<Integer>resultList){
booleanf=false;
while(num%p==0){
num/=p;
f=true;
}
if(f){
resultList.add(p);
}
returnnum;
}
privateintgetNextPrimeNumber(){
if(this.primeList.size()>index++){
returnthis.primeList.get(index-1);
}
intnext=this.primeList.get(this.primeList.size()-1)+2;
while(true){
intstop=(int)Math.floor(Math.sqrt(next));
booleanf=true;
for(intn:this.primeList){
if(n>stop){
break;
}
if(next%n==0){
f=false;
break;
}
}
if(f){
this.primeList.add(next);
break;
}else{
next+=2;
}
}
returnnext;
}
publicstaticvoidmain(String[]args){
Solutions=newSolution(123);
System.out.println(s.findPrimeContainedList());
s.setNum(240);
System.out.println(s.findPrimeContainedList());
}
}
好久没写JAVA了。逻辑很简单,做了点优化。
④ 用java输入一个数字,打印其所有因子,包含1但不包含自己,并对所有因子求和
import java.util.Scanner;
public class FactorsOfNumberUsingFor {
private static Scanner sc;
public static void main(String[] args) {
int Number, i,sum=0;
sc = new Scanner(System.in);
System.out.println("输入一个整数: ");
Number = sc.nextInt();
for(i = 1; i <= Number; i++) {
if(Number%i == 0) {
sum+=i;
System.out.format(" %d ", i);
}
}
}
}