#Program to find nth number which is divisible by the square of a prime isn't working

3 messages · Page 1 of 1 (latest)

teal galleonBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

onyx hatch
#

!format

teal galleonBOT
#
#include <cmath>
#include <iostream>

using namespace std;

// Function to check if a number is prime
bool isPrime(int n) {
  if (n <= 1)
    return false;

  for (int i = 2; i <= sqrt(n); i++)
    if (n % i == 0)
      return false;

  return true;
}

// Function to find the nth number divisible by the square of a prime factor
int findNthNumber(int n) {
  int ans;
  int num = 4;
  while (n > 0) {
    for (int j = 2; j < num; j++) {
      if (isPrime(j)) {
        if (num % j == 0) {
          n--;
          break;
        }
      }
    }
    num++;
  }
  ans = num - 1;
  return ans;
}
int main() {
  int n;
  cout << "Enter the value of n: ";
  cin >> n;

  int num = findNthNumber(n);
  cout << "The nth number is: " << num << endl;

  return 0;
}
Darkknight