Fakultät probleme

attex

Mitglied
Hei Leute,

hab hier zwei Prgramme geschrieben, die komischerweise nicht funktionieren und ich weiß leider nicht genau woran das liegt.

Hier mal die Aufgabe vom ersten Programm:

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?

und das ist mein Code:

Java:
public class main3 {
 public static void main(String [] args){
	 double num = 0;
	 int sum = 0;
	 num = Math.pow(2, 1000);
	 System.out.println(num);
	 while(num >= 1){
		 sum += num % 10;
	         num = num / 10;
	 }
	 System.out.println(sum);
 }
}

für das Bsp. 2^15 funktioniert das aber für das andere nicht hat jemand n plan wieso nicht sonst?
und beim zweiten ist das auch ganz ähnlich:

n! means n × (n − 1) × ... × 3 × 2 × 1

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!


Java:
public class main2 {
 public static void main(String [] args){
	 double sum = 1 ;
	 int sum2 = 0;
	 for(int i=100; i>0; i--){
		 sum *= i;
		 
	 }
	 while(sum > 1){
		System.out.println(sum);
		sum2 += sum % 10;
		System.out.println(sum2);
		sum = sum / 10;
		
	 }
	 
	 System.out.println(sum2);
	 
 }
}

weiß jemand woran das liegt?


Beste grüße
 
Ja, overflow. Die Werte werden zu groß und können nicht mehr exakt gespeichert werden.

Du kannst natürlich ganz einfach BigDecimal bzw Bignteger verwenden, aber offenbar sollst du dir hier einen gescheiten Algorithmus überlegen, wie das Problem auch ohne zuhilfename dieser Klassen lösen kannst.
 

Zurück
Oben