Can someone help me | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone help me

I've been trying throughout this entire day to get the prime factors of a number, but my code has not been working. https://code.sololearn.com/cjx8QBMb8MmH/?ref=app

7th Sep 2020, 10:00 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar
8 Answers
+ 2
Joseph Oritseweyinmi you're welcome.. If you not competed yet, then try that way.. I will add complete my code if you stuck or give reply to compare codes if you want later.. Edit: //function way, hope it more clears... class Program { public static void prime(int input) { for (int x = 2;x < input;x++) { if(input%x == 0 && isPrime(x)) Console.WriteLine(x); } } static bool isPrime(int x) { for( int i=2; i<=x/2; i++) if(x%i== 0) return false; return true; } static void Main(string[] args) { prime(10); } }
7th Sep 2020, 10:47 PM
Jayakrishna 🇮🇳
+ 2
You are performing x % y, after the for loop y = x-1, on the second iteration y becomes 0 and causes the program to crash because you cant divide by zero. The modulus acts as a division even though its giving you a remainder
7th Sep 2020, 10:25 PM
Robert Atkins
Robert Atkins - avatar
+ 2
Check your second for loop you have the condition as y = x-1; x > 0; y--, was that x meant to be a y
7th Sep 2020, 10:34 PM
Robert Atkins
Robert Atkins - avatar
+ 2
You have a lot of redudent code, actually what is the need of 2nd for loop and it's if else, both saying just continue so 3rd for loop not reachable at all.. Make it clear and simple.. Start a for loop, then if that is factor of input then find if it is prime or not, if yes print otherwise go next.. So separate the prime checking in another function so it more add clarity... Like this for(int i =2; i<input; i++) If(input%i==0 && isprime(i) Console.WriteLine(I); Just add is prime function here, everything will complete... Edit : bool b = true; for (int x = 2;x < input;x++) { if(input%x==0) for(int i =2; i<= x/2; i++) if(x%i == 0){ b = false; break; } if(b) Console.WriteLine(x); } }
7th Sep 2020, 10:36 PM
Jayakrishna 🇮🇳
+ 2
You have to also ensure y doesnt equal 0 either or else youll get a divide by zero error
7th Sep 2020, 10:37 PM
Robert Atkins
Robert Atkins - avatar
+ 1
Thanks, but how do i fix it
7th Sep 2020, 10:29 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar
+ 1
Thank you so much guys
7th Sep 2020, 10:39 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar
0
No it's meant to be x
7th Sep 2020, 10:35 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar