Prüfen ob die Zahl eine Primzahl ist
-
Guten Tag,
normal würde ich mit der Aufgabe zurecht kommen, aber bin wohl ein bisschen eingerostet oder ich übersehe einen kleinen Fehler.#include <iostream> #include <fstream> int main() { std::fstream file; file.open("Prim.txt", std::ios::out); int counter = 0; for(int i = 2; i < 10; i++) //die zu prüfende Primzahl { for(int j = 2; j < i; j++) //Schleife damit diese Zahl durch jede geteilt wird { if(i != j) //damit sie sich nicht durch sich selbst teilt { if(i % j != 0) //entsteht Rest, dann counter++ { counter++; } } if(i == counter) //wenn Counter so groß wie die Zahl ist, ist es eine Primzahl { file << i; } } counter = 0; } file.close(); }
Mein Problem ist nun, dass keine Zahl in die Datei geschrieben wird. Hoffe mir kann jemand helfen...
-
if(i == counter) //wenn Counter so groß wie die Zahl ist, ist es eine Primzahl
Eben nicht, da du allein schon die 1 und i weglässt, kannst du i nicht erreichen.
-
Das hieße rein theoretisch das ich einfach if(i == counter + 2) schreiben müsste, was aber nicht klappt oder nicht?
-
#include <iostream> #include <fstream> int main() { std::fstream file; file.open("Prim.txt", std::ios::out); for(int i = 2; i < 10; i++) //die zu prüfende Primzahl { bool isPrime = true; for(int j = 2; isPrime && j < i; j++) //Schleife damit diese Zahl durch jede geteilt wird { if(i != j) //damit sie sich nicht durch sich selbst teilt { isPrime = !!(i % j); } } if (isPrime) file << i << " "; } file.close(); }
-
-
FreakY<3Cpp schrieb:
Das hieße rein theoretisch das ich einfach if(i == counter + 2) schreiben müsste, was aber nicht klappt oder nicht?
ausprobieren?
-
Kuldren schrieb:
FreakY<3Cpp schrieb:
Das hieße rein theoretisch das ich einfach if(i == counter + 2) schreiben müsste, was aber nicht klappt oder nicht?
ausprobieren?
Als wenn ich es net gemacht habe ^^
Fellhuhn schrieb:
#include <iostream> #include <fstream> int main() { std::fstream file; file.open("Prim.txt", std::ios::out); for(int i = 2; i < 10; i++) //die zu prüfende Primzahl { bool isPrime = true; for(int j = 2; isPrime && j < i; j++) //Schleife damit diese Zahl durch jede geteilt wird { if(i != j) //damit sie sich nicht durch sich selbst teilt { isPrime = !!(i % j); } } if (isPrime) file << i << " "; } file.close(); }
Thx Fellhuhn, funktioniert...